Java / Micronaut Interview questions
How do you handle exceptions globally in a Micronaut application?
Micronaut handles global exceptions through ExceptionHandler beans rather than a single catch-all annotation on a controller class.
@Produces @Singleton @Requires(classes = OrderNotFoundException.class) public class OrderNotFoundHandler implements ExceptionHandler<OrderNotFoundException, HttpResponse<?>> { public HttpResponse<?> handle(HttpRequest request, OrderNotFoundException e) { return HttpResponse.notFound( Map.of("error", e.getMessage())); } }
Registering this as a bean means any controller in the application that throws OrderNotFoundException gets routed through this handler automatically, converting it into a consistent JSON error response, with no need to wrap every controller method in try/catch.
For validation and framework-level errors, Micronaut also provides built-in handlers you can override, and a catch-all handler for uncaught Throwable can be registered the same way to guarantee no exception ever leaks a raw stack trace to a client.
More Related questions...