ExceptionHandler
Additionally you can implement a ExceptionHandler; a generic hook for handling exceptions that occurs during the execution of an HTTP request.
Imagine your e-commerce app throws an OutOfStockException
when a book is out of stock:
public class OutOfStockException extends RuntimeException {
}
class OutOfStockException extends RuntimeException {
}
class OutOfStockException : RuntimeException()
Along with BookController
:
@Controller("/books")
public class BookController {
@Produces(MediaType.TEXT_PLAIN)
@Get("/stock/{isbn}")
Integer stock(String isbn) {
throw new OutOfStockException();
}
}
@Controller("/books")
class BookController {
@Produces(MediaType.TEXT_PLAIN)
@Get("/stock/{isbn}")
Integer stock(String isbn) {
throw new OutOfStockException()
}
}
@Controller("/books")
class BookController {
@Produces(MediaType.TEXT_PLAIN)
@Get("/stock/{isbn}")
internal fun stock(isbn: String): Int? {
throw OutOfStockException()
}
}
If you don’t handle the exception the server returns a 500 (Internal Server Error) status code.
If you want to respond 200 OK with 0 (stock level) as the response body when the OutOfStockException
is thrown, you could register a ExceptionHandler
:
@Produces
@Singleton
@Requires(classes = {OutOfStockException.class, ExceptionHandler.class})
public class OutOfStockExceptionHandler implements ExceptionHandler<OutOfStockException, HttpResponse> {
@Override
public HttpResponse handle(HttpRequest request, OutOfStockException exception) {
return HttpResponse.ok(0);
}
}
@Produces
@Singleton
@Requires(classes = [OutOfStockException.class, ExceptionHandler.class])
class OutOfStockExceptionHandler implements ExceptionHandler<OutOfStockException, HttpResponse> {
@Override
HttpResponse handle(HttpRequest request, OutOfStockException exception) {
HttpResponse.ok(0)
}
}
@Produces
@Singleton
@Requirements(
Requires(classes = [OutOfStockException::class, ExceptionHandler::class])
)
class OutOfStockExceptionHandler : ExceptionHandler<OutOfStockException, HttpResponse<*>> {
override fun handle(request: HttpRequest<*>, exception: OutOfStockException): HttpResponse<*> {
return HttpResponse.ok(0)
}
}
An @Error annotation capturing an exception has precedence over an implementation of ExceptionHandler capturing the same exception. |