Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 ยท HTTP Server and Clients

Filters and Error Handling

Run code around every request with Micronaut HTTP filters, and turn exceptions into clean JSON errors with @Error and ExceptionHandler. Runnable Java stand-ins included.

Two jobs show up in every web service: doing something for many requests at once (logging, adding headers, checking an API key), and turning failures into clear responses. Micronaut solves the first with filters and the second with exception handlers and @Error methods.

Micronaut is not installed on this site, so the framework code is read-only. The runnable programs are plain-Java stand-ins: a filter chain that wraps a handler, and an exception-to-response mapper. They show the control flow, which is what matters.

Server filters

A filter sees a request before a controller does and sees the response on the way back. In recent Micronaut versions you write filters with annotated methods:

Java
import io.micronaut.http.HttpRequest;
import io.micronaut.http.MutableHttpResponse;
import io.micronaut.http.annotation.RequestFilter;
import io.micronaut.http.annotation.ResponseFilter;
import io.micronaut.http.annotation.ServerFilter;

@ServerFilter("/api/**")
public class AuditFilter {

    @RequestFilter
    public void before(HttpRequest<?> request) {
        System.out.println("-> " + request.getMethod() + " " + request.getPath());
    }

    @ResponseFilter
    public void after(HttpRequest<?> request, MutableHttpResponse<?> response) {
        response.getHeaders().add("X-Served-By", "orders-service");
        System.out.println("<- " + response.status().getCode());
    }
}

@ServerFilter("/api/**") limits the filter to matching paths. @RequestFilter methods run before the route; @ResponseFilter methods run after it. A request filter can also return a response to stop the request early, for example HttpResponse.status(HttpStatus.UNAUTHORIZED) when an API key is missing. The older HttpServerFilter interface with doFilter(request, chain) still works and gives you the chain object directly.

Filters are chained, so their order matters; set it with the @Order annotation or by implementing Ordered. Security, which is a filter itself, runs early so that your later filters can read the authenticated user (see security fundamentals).

flowchart LR
    C["Client"] --> F1["Request filter 1"]
    F1 --> F2["Request filter 2"]
    F2 --> R["Controller"]
    R --> G2["Response filter 2"]
    G2 --> G1["Response filter 1"]
    G1 --> C2["Client"]

Request filters run in order, response filters run in reverse.

Client filters

The same idea exists for outgoing calls. A @ClientFilter("/inventory/**") can add an authorization header to every call a declarative client makes, so you do not repeat the header on each method.

Handling errors

When a controller throws, Micronaut looks for a handler. By default you get a JSON body with a message and the status code. To shape it yourself, there are three tools.

@Error methods in a controller

Java
@Controller("/books")
public class BookController {

    @Get("/{id}")
    Book find(long id) {
        return repo.findById(id).orElseThrow(() -> new BookNotFoundException(id));
    }

    @Error
    public HttpResponse<ApiError> onNotFound(HttpRequest<?> request, BookNotFoundException e) {
        return HttpResponse.notFound(new ApiError("not_found", e.getMessage(), request.getPath()));
    }
}

An @Error method with a specific exception type handles errors from that controller only. @Error(global = true) handles them from every controller. You can also handle an HTTP status instead of an exception: @Error(status = HttpStatus.NOT_FOUND) runs for any 404, including unknown URLs.

ExceptionHandler beans

For a reusable rule across the whole application, write a bean:

Java
@Produces
@Singleton
@Requires(classes = {BookNotFoundException.class, ExceptionHandler.class})
public class BookNotFoundHandler implements ExceptionHandler<BookNotFoundException, HttpResponse<ApiError>> {

    @Override
    public HttpResponse<ApiError> handle(HttpRequest request, BookNotFoundException e) {
        return HttpResponse.notFound(new ApiError("not_found", e.getMessage(), request.getPath()));
    }
}

Micronaut already has handlers for common exceptions: a ConstraintViolationException becomes 400, invalid JSON becomes 400, and an unsupported content type becomes 415. Your handler for a more specific type wins over a general one.

One error shape

Pick a single JSON shape for errors and use it everywhere. A small record is enough:

Java
@Serdeable
public record ApiError(String code, String message, String path) {}

Clients then parse errors with one class, and you never leak a stack trace. Use 500 handlers carefully: log the real exception on the server, but return only a generic message and, if useful, a correlation id.

Filters or handlers?

Filter Runs for many requests, before and after.
Handler Runs only when something throws.
@Error Local to one controller.

Use the smallest tool that fits.

1 / 2

Stand-in 1: a filter chain around a handler

This program builds a request/response pipeline by hand. Two filters wrap a handler: one logs and times the call (the time is a fake counter so the output is stable), one rejects requests without an API key before the handler runs. It shows the same ordering rule as Micronaut: request filters in order, response work in reverse.

Java Request and response filters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The audit filter is first in the list, so it wraps everything, including the rejection. That is why even the 401 gets the X-Served-By header. If you swapped the two filters, rejected requests would never be logged. Micronaut gives you the same choice through @Order.

Stand-in 2: mapping exceptions to responses

Here a registry maps exception types to handler functions, and the dispatcher picks the most specific match by walking up the exception's class hierarchy. This is how @Error and ExceptionHandler beans are chosen.

Java Choosing the most specific exception handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the last error: a NullPointerException has no handler, so the caller gets a safe generic 500 and no internal detail. Real Micronaut does the same by default, and you should log the original exception on the server so you can still find the bug.

Practical advice

  • Prefer filters for cross-cutting request rules, such as correlation ids, rate limits and header rewriting. Prefer AOP interceptors when the rule is about a method rather than a URL.
  • Keep filters fast and non-blocking. They run on the request path of every matching call.
  • Do not catch exceptions in every controller. Throw domain exceptions and handle them once.
  • Return the right status. 404 for a missing resource, 409 for conflicts, 422 or 400 for invalid input, 5xx only for server faults.
  • Test the error paths. A test that calls a bad URL and reads the JSON body is cheap and catches contract changes; see testing with Micronaut Test.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which annotation limits a filter class to certain URL paths?

    @ServerFilter takes a path pattern. @Order only sets where the filter sits in the chain.
  2. 2. A request filter wants to refuse a request before the controller runs. What can it do?

    A request filter may produce a response itself, which ends processing early.
  3. 3. What does @Error(global = true) do?

    A non-global @Error method handles errors from its own controller only. Global makes it application-wide.
  4. 4. Why return a generic message for an unexpected 500?

    Log the details on the server and give the client a safe message, optionally with a correlation id.

Summary

  • Filters run code around many requests; use @ServerFilter, @RequestFilter and @ResponseFilter, and set the order with @Order.
  • A request filter can end the request early by returning a response.
  • Exceptions are handled by @Error methods (per controller or global) and by ExceptionHandler beans.
  • The most specific handler for the exception type wins.
  • Use one error JSON shape across the service and never leak stack traces.
  • Client filters add headers or credentials to outgoing calls in one place.

Next: Streaming, Server-Sent Events and Async