Interface ServerErrorHandler

Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

@UnstableApi @FunctionalInterface public interface ServerErrorHandler
Provides the error responses in case of unexpected exceptions or protocol errors. Implement this interface to customize Armeria's error responses.

 ServerErrorHandler errorHandler = (ctx, cause) -> {
     if (cause instanceof IllegalArgumentException) {
         return HttpResponse.of(HttpStatus.BAD_REQUEST);
     }

     // You can return a different response using the path.
     if ("/outage".equals(ctx.path())) {
         return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR,
                                MediaType.PLAIN_TEXT, "Oops, something went wrong.");
     }

     // Return null to let ServerErrorHandler.ofDefault() handle the exception.
     return null;
 }

 Server.builder().errorHandler(errorHandler)...
 

Recording a service exception (or not)

By default, an exception raised by a service or a decorator is captured and recorded into RequestLog.responseCause(). You can keep Armeria from recording it while sending the desired response by returning a failed response whose cause is an HttpStatusException or HttpResponseException:


 ServerErrorHandler errorHandler = (ctx, cause) -> {
     if (cause instanceof IllegalArgumentException) {
         // IllegalArgumentException is captured into RequestLog#responseCause().
         return HttpResponse.of(HttpStatus.BAD_REQUEST);
     }

     if (cause instanceof NotFoundException) {
         // NotFoundException is NOT captured into RequestLog#responseCause().
         return HttpResponse.ofFailure(HttpStatusException.of(HttpStatus.NOT_FOUND));
     }
     ...
 }
 
See Also: