Introduction
Exception filters
Turn exceptions into responses, per route, per controller or for the whole application.
A filter turns an exception into a response. Throw from anywhere in a handler, guard, pipe or interceptor; the filter decides what the client sees.
@Catch(PaymentFailed::class) // which exceptions it handles; no @Injectable needed
class PaymentFilter : ExceptionFilter {
override suspend fun catch(exception: Throwable, ctx: ExecutionContext): HttpResponse? =
HttpResponse(402, mapOf("content-type" to "application/json"), """{"error":"payment"}""".toByteArray())
}
@Controller("/orders")
class OrdersController {
@Get("/pay") @UseFilters(PaymentFilter::class) fun pay(): String = throw PaymentFailed("E1") // on one route
}
@UseFilters(PaymentFilter::class) class AllOrders { ... } // or on a whole controllerList the filter in a module's providers. Three ways to attach it:
| Where | How |
|---|---|
| one handler or a whole controller | @UseFilters(PaymentFilter::class) |
| every route, chosen when starting the server | useFilters(PaymentFilter::class) |
| every route, declared on the class | @Catch(PaymentFailed::class, global = true) (NestJS APP_FILTER) |
@Catchwith no types, or no@Catchat all, handles every exception. You can also overridecatchesyourself.- Return
nullto decline: the next filter is tried, and if none answers, the default JSON error (anHttpExceptionkeeps its status; anything else is a logged 500) is sent. - Order: handler filters, controller filters, global filters (
useFiltersfirst, then@Catch(global = true)), controller advice, then the default. - The
ExecutionContextgives the request, the principal and the handler's annotations, so a filter can answer differently for different routes. - Filters run for HTTP, and also for microservice, WebSocket and gRPC handlers. GraphQL resolvers report errors as GraphQL errors with
extensions.codeinstead (see GraphQL).
Filters or controller advice? They do the same job: turn an exception into a response. Use whichever reads better, and mix them freely.
- Filters (NestJS style): one class per exception type, attached to a route, a controller, or globally with
@Catch(global = true). - Controller advice (Spring style): one class holding several
@ExceptionHandlermethods that map your whole API's errors in one place. Filters run first, advice second, so a route-specific filter can override what the advice would do.
Built in: the default handler and the framework's exceptions
You do not have to write a filter to get good errors. Kest has a built-in handler (NestJS BaseExceptionFilter) that answers whenever no filter or advice does, and a family of exceptions to throw. Throw one from anywhere and the client gets the standard JSON:
@Get("/{id}") fun find(@Param id: String): Order = orders.find(id) ?: throw NotFoundException("order $id not found"){ "statusCode": 404, "message": "order 9 not found", "error": "Not Found" }| Exception | Status | Exception | Status | |
|---|---|---|---|---|
BadRequestException | 400 | UnprocessableEntityException | 422 | |
UnauthorizedException | 401 | TooManyRequestsException | 429 | |
ForbiddenException | 403 | InternalServerErrorException | 500 | |
NotFoundException | 404 | NotImplementedException | 501 | |
MethodNotAllowedException | 405 | BadGatewayException | 502 | |
NotAcceptableException | 406 | ServiceUnavailableException | 503 | |
RequestTimeoutException | 408 | GatewayTimeoutException | 504 | |
ConflictException | 409 | HttpVersionNotSupportedException | 505 | |
GoneException | 410 | ImATeapotException | 418 | |
PreconditionFailedException | 412 | MisdirectedException | 421 | |
PayloadTooLargeException | 413 | UnsupportedMediaTypeException | 415 |
Each takes an optional message (ForbiddenException("admins only")). For any other status use HttpException(status, message); give it a details list and message becomes an array (validation does this, one entry per failed rule). All of them are open, so you can build your own on top and keep the status:
class OrderNotFound(id: String) : NotFoundException("order $id not found") // still a 404 with the standard bodyWhat the built-in handler does with each kind of exception:
| Thrown | Answer |
|---|---|
an HttpException (any of the above, validation, authentication) | its status and the standard body |
| an invalid page or sort request | 400 with the reason |
| anything else | logged, reported to every ErrorReporter (Sentry), and answered 500 Internal server error: the real message is never sent to the client |
Extend it
Subclass BaseExceptionFilter to add your own behaviour (auditing, a header, a metric) and still get the standard answers: do your part, then delegate with super.catch:
@Catch(global = true) // every route
class AuditingFilter(private val audit: AuditLog) : BaseExceptionFilter() {
override suspend fun catch(exception: Throwable, ctx: ExecutionContext): HttpResponse? {
audit.record(ctx.request.path, exception)
return super.catch(exception, ctx) // the standard JSON error, and reporting of unexpected errors
}
}Narrow it with @Catch(SomeException::class) and the standard handler still answers everything else. Override respond(exception, request, extraHeaders) instead to change only the body while keeping the logging and reporting.
Controller advice
Spring's @ControllerAdvice for exceptions. Exception filters attach to a route or controller; advice handles every controller, in one class:
@ControllerAdvice
class ApiErrors {
@ExceptionHandler(OrderNotFound::class) @ResponseStatus(404)
fun notFound(e: OrderNotFound) = mapOf("error" to "order_not_found", "id" to e.id)
@ExceptionHandler fun stock(e: OutOfStock, request: HttpRequest) = HttpResponse(409, ..., ...) // a whole response
@ExceptionHandler fun fallback(e: Exception) = mapOf("error" to "internal") // everything else
}
@Module(providers = [ApiErrors::class], controllers = [...]) class AppModuleHandlers take the exception, and optionally the HttpRequest or ExecutionContext. The handler for the most specific exception type wins. The status is @ResponseStatus, else the exception's own status when it is an HttpException, else 500.
Order: filters on the handler, then on the controller, then global useFilters, then advice, then the framework's default JSON error. Advice also sees 404s, 405s, validation and authentication errors.