Skip to content

Error Handling ​

Introduction ​

When something goes wrong during a request, the framework needs to do two things: record the problem, and send the client a sensible response. In Plinth both are the job of the ExceptionHandler from @plinthjs/http. The HttpKernel catches anything thrown by a handler or route middleware, passes it to the handler to be reported, then asks the handler to render it as a Response. Because this happens inside the pipeline, your global middleware always receive a real response from next(), even for failed requests.

You normally customize error handling in one place: where the handler is created.

Throwing HTTP errors ​

Throw an HttpException with a status, an optional message and optional headers, from a handler, middleware or any code called by them:

ts
import { HttpException, NotFoundHttpException, Router } from '@plinthjs/http'

const router = new Router()

router.get('/posts/{id}', async (req) => {
  const post = await findPost(req.param('id')!)
  if (post === null) throw new NotFoundHttpException() // 404
  if (!post.published) throw new HttpException(403, 'This post is not published.')
  return post
})

router.get('/teapot', () => {
  throw new HttpException(418, "I'm a teapot", { 'X-Tea': 'yes' }) // custom headers
})

HttpException(status, message?, headers?) is the general form. The subclasses NotFoundHttpException (404, default message Not Found) and MethodNotAllowedHttpException (405, takes the list of allowed verbs and sets Allow) are what the kernel itself throws for unmatched routes.

Three helpers throw an HttpException for you, from anywhere in a request:

ts
import { abort, abortIf, abortUnless } from '@plinthjs/http'

abort(404) // message defaults to the reason phrase: 'Not Found'
abort(403, 'Not your post')
abortIf(post.archived, 410, 'This post is gone')
abortUnless(user.isAdmin, 403)

abort(status, message?, headers?) never returns. abortIf and abortUnless take the condition first and the same remaining arguments. Plain throw new HttpException(...) works the same way.

Not found and method not allowed errors are produced automatically:

ts
import { HttpKernel, Request } from '@plinthjs/http'

const kernel = new HttpKernel(router)
const res = await kernel.handle(new Request({ url: '/nope' }))
res.status // => 404

How errors are rendered ​

By default the handler negotiates the response format. If the request wants JSON (an Accept header containing /json or +json, or an XMLHttpRequest header), the body is JSON. Otherwise it is a small HTML page.

ts
// Accept: application/json
// => 404 {"message":"Not Found","status":404}

// Accept: text/html
// => 404 <!doctype html>... <h1>404 Not Found</h1><p>Not Found</p>

The status comes from the exception: an HttpException's status, a numeric status property carried by any error object, or 500 for everything else. Headers given to the exception are added to the response. The message is HTML-escaped in the HTML page.

Unexpected errors are not leaked. A plain Error that reaches the handler renders as 500 Internal Server Error with no detail, because its message might contain secrets.

Debug mode ​

Construct the handler with true to expose details for local development. Non-HTTP errors then show their real message, and JSON responses gain an exception field with the stack.

ts
import { ExceptionHandler } from '@plinthjs/http'

const handler = new ExceptionHandler(process.env.APP_DEBUG === 'true')

WARNING

Never enable debug mode in production: stack traces and messages reveal internals. The scaffolded application reads app.debug from its configuration, see Configuration.

Installing a handler ​

Give the handler to the kernel directly, or bind it in the container under the EXCEPTION_HANDLER token. The kernel prefers an explicit option, then the container binding, then a fresh default handler.

ts
import { EXCEPTION_HANDLER, ExceptionHandler, HttpKernel } from '@plinthjs/http'

new HttpKernel(router, { exceptionHandler: handler })

// or, from a service provider
app.singleton(EXCEPTION_HANDLER, () => handler)
new HttpKernel(router, { container: app })

The scaffolded AppServiceProvider binds the handler this way, sets debug mode from app.debug, and reports through the application logger. See Providers and Logging.

Reporting exceptions ​

Reporting means telling someone: logging, sending to an error tracker, alerting. By default the report sink does nothing, so you opt in with reportUsing():

ts
handler.reportUsing((error, context) => {
  logger.error(String(error instanceof Error ? error.stack : error), context)
})

The sink receives the error and a context object that always contains the level (see below) plus whatever context() returns. Override context() in a subclass to attach request-scoped information:

ts
class AppHandler extends ExceptionHandler {
  override context() {
    return { app: 'shop' }
  }
}

Custom reporters ​

reportable() adds a callback that runs for every reported error before the sink. Return false to stop all further reporting of that error (including the sink):

ts
handler.reportable((error) => {
  if (error instanceof PaymentGatewayError) {
    alertOnCall(error)
    return false // do not also log it normally
  }
})

Exceptions that are not reported ​

HttpException and all its subclasses (404, 405, ...) are not reported by default, since they are ordinary outcomes. Validation failures are ignored too (see below). Add your own with dontReport() (alias ignore()). Matching uses instanceof, so a base class also covers its subclasses. Use stopIgnoring() to start reporting a class again.

ts
handler.dontReport(PaymentDeclinedError)
handler.stopIgnoring(NotFoundHttpException) // actually do report 404s
handler.shouldReport(new PaymentDeclinedError()) // => false

TIP

Validation failures are in the default ignore list, so a failed validation is not reported at error level. They are matched structurally (a ValidationError name, or status 422 carrying an errors bag), so the http package needs no validation dependency. To report them anyway, call handler.stopIgnoring(ValidationError).

Log levels ​

level() sets the severity an exception class is reported at. The level reaches your sink as context.level, defaulting to 'error'. The available levels are debug, info, notice, warning, error, critical, alert and emergency.

ts
handler.level(GatewayDownError, 'critical').level(RateLimitError, 'warning')

handler.levelFor(new GatewayDownError()) // => 'critical'

Avoiding duplicate reports ​

If the same error instance can reach the handler more than once, for example because it is rethrown, call withoutDuplicates() so each instance is reported once.

ts
handler.withoutDuplicates()

Mapping exceptions ​

map() converts one kind of error into another before it is reported and rendered. It is the cleanest way to turn a library or domain error into the right HTTP error without try and catch in your handlers. The first matching mapping wins.

ts
handler.map(TypeError, (error) => new HttpException(400, `Bad input: ${error.message}`))
handler.map(RecordNotFoundError, () => new NotFoundHttpException())

Because the mapped error is what gets reported, a mapping to an HttpException also means the error is not reported (HTTP exceptions are on the ignore list).

Custom renderable exceptions ​

renderable() registers a callback that produces a response for a specific error. Callbacks are tried in order. Return a Response to use it, or undefined to fall through to the next callback and finally the default rendering.

ts
import { Response } from '@plinthjs/http'

handler.renderable((error, req) => {
  if (error instanceof GatewayDownError) {
    return Response.json({ message: 'Try again shortly.' }, 503).header('Retry-After', '30')
  }
})

Since a renderable receives the request, it can pick between formats with req.wantsJson(). The same hook is how you render your own error pages in place of the default HTML.

Validation and authorization errors ​

The handler does not depend on the validation or authorization packages. It recognizes their errors by shape: a numeric status property sets the response status, and an errors object is treated as a validation bag. As a result:

  • A ValidationError from Validation has status 422. For clients that want JSON the response is 422 with { "message": "...", "status": 422, "errors": { "field": ["..."] } }.
  • For a browser (an HTML request), a validation error becomes a redirect back to the Referer (or /), with the errors flashed under errors and the submitted input flashed as old input. The session middleware stores them for the next page.
  • An AuthorizationError carries status 403 and renders as a 403 page or JSON, see Authorization.
ts
import { validate } from '@plinthjs/validation'

router.post('/signup', async (req) => {
  const data = await validate(req, { email: 'required|email', password: 'required|min:8' })
  return createUser(data)
})
// JSON client, bad input => 422 {"message":"The given data was invalid.","status":422,"errors":{...}}
// Browser, bad input    => 302 to the referring page, errors and old input flashed

So a controller needs no try and catch around validation. Your own errors can use the same mechanism: give a class a numeric status property and it renders at that status without extending HttpException.

ts
class PaymentRequired extends Error {
  readonly status = 402
}
// throw new PaymentRequired('Upgrade your plan') => 402

Keeping secrets out of flashed input ​

When the handler redirects a failed validation, it flashes the request input except for the keys in its dontFlash list, which defaults to current_password, password and password_confirmation. Replace the list with dontFlash():

ts
handler.dontFlash(['password', 'password_confirmation', 'card_number'])
handler.getDontFlash() // => ['password', 'password_confirmation', 'card_number']

Forcing JSON for an API ​

For an API you almost always want JSON errors, including for validation failures that would otherwise redirect. Add a global middleware that sets the Accept header, as the scaffolded API application does:

ts
import type { Middleware } from '@plinthjs/http'

export function forceJson(): Middleware {
  return (request, next) => next(request.withHeader('accept', 'application/json'))
}

Errors in middleware and streaming ​

An error thrown by global middleware is also caught, reported and rendered by the kernel. Terminable middleware run after the response exists, and a failure in one does not stop the rest. A streamed response cannot change its status once streaming has started. See Responses.

Testing error handling ​

Call the kernel with a synthetic request and look at the response. No server is needed:

ts
const kernel = new HttpKernel(router, { exceptionHandler: new ExceptionHandler(false) })

const res = await kernel.handle(
  new Request({ url: '/boom', headers: { accept: 'application/json' } }),
)
res.status // => 500
res.body // => '{"message":"Internal Server Error","status":500}'

handler.render(req, error) and handler.report(error) can also be called directly, and handler.statusFor(error) tells you which status an error would produce.

Released under the MIT License.