Kest

Search

Search the documentation

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 controller

List the filter in a module's providers. Three ways to attach it:

WhereHow
one handler or a whole controller@UseFilters(PaymentFilter::class)
every route, chosen when starting the serveruseFilters(PaymentFilter::class)
every route, declared on the class@Catch(PaymentFailed::class, global = true) (NestJS APP_FILTER)
  • @Catch with no types, or no @Catch at all, handles every exception. You can also override catches yourself.
  • Return null to decline: the next filter is tried, and if none answers, the default JSON error (an HttpException keeps its status; anything else is a logged 500) is sent.
  • Order: handler filters, controller filters, global filters (useFilters first, then @Catch(global = true)), controller advice, then the default.
  • The ExecutionContext gives 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.code instead (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 @ExceptionHandler methods 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" }
ExceptionStatusExceptionStatus
BadRequestException400UnprocessableEntityException422
UnauthorizedException401TooManyRequestsException429
ForbiddenException403InternalServerErrorException500
NotFoundException404NotImplementedException501
MethodNotAllowedException405BadGatewayException502
NotAcceptableException406ServiceUnavailableException503
RequestTimeoutException408GatewayTimeoutException504
ConflictException409HttpVersionNotSupportedException505
GoneException410ImATeapotException418
PreconditionFailedException412MisdirectedException421
PayloadTooLargeException413UnsupportedMediaTypeException415

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 body

What the built-in handler does with each kind of exception:

ThrownAnswer
an HttpException (any of the above, validation, authentication)its status and the standard body
an invalid page or sort request400 with the reason
anything elselogged, 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 AppModule

Handlers 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.

Read more