How to Return 404 with Spring WebFlux

1. Overview

With Spring Boot 2 and the new non-blocking server Netty, we don’t have the Servlet context API anymore, so let’s discuss the way how we can express different kind of HTTP status codes, using the new stack.

2. Semantic Response Status

Follow standard RESTful practice, we naturally need to make use of the full range of HTTP status codes to express the semantics of the API properly.

2.1. Default Return Status

Of course, when everything goes well, the default response status is the 200 (OK):

@GetMapping(
  value = "/ok",
  produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public Flux<String> ok() {
    return Flux.just("ok");
}

2.2. Using Annotations

We can alter the default return status adding the @ResponseStatus annotation to the method:

@GetMapping(
  value = "/no-content",
  produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
@ResponseStatus(HttpStatus.NO_CONTENT)
public Flux<String> noContent() {
    return Flux.empty();
}

2.3. Changing the Status Programmatically

In some cases, depending on our server’s behavior, we could decide to change the returned status programmatically instead of a prefixed returned status used by default or with annotations.

We can achieve that injecting ServerHttpResponse in our method directly:

@GetMapping(
  value = "/accepted",
  produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public Flux<String> accepted(ServerHttpResponse response) {
    response.setStatusCode(HttpStatus.ACCEPTED);
    return Flux.just("accepted");
}

Now we can choose which HTTP status code we return right in the implementation.

2.4. Throwing an Exception

Any time we throw an exception, the default HTTP return status is omitted and Spring tries to find an exception handler to deal with it:

@GetMapping(
  value = "/bad-request"
)
public Mono<String> badRequest() {
    return Mono.error(new IllegalArgumentException());
}
@ResponseStatus(
  value = HttpStatus.BAD_REQUEST,
  reason = "Illegal arguments")
@ExceptionHandler(IllegalArgumentException.class)
public void illegalArgumentHandler() {
    // 
}

To learn more about how to do that, definitely check-out the Error Handling article on VietMX’s Blog.

2.5. With ResponseEntity

Let’s now have a quick look at an interesting alternative – the ResponseEntity class.

This allows us to choose which HTTP status we want to return and also to customize our responses much further, using a very useful fluent API:

@GetMapping(
  value = "/unauthorized"
)
public ResponseEntity<Mono<String>> unathorized() {
    return ResponseEntity
      .status(HttpStatus.UNAUTHORIZED)
      .header("X-Reason", "user-invalid")
      .body(Mono.just("unauthorized"));
}

2.6. With Functionals Endpoints

With Spring 5, we can define endpoints in a functional way, so, we can change the default HTTP status programmatically as well:

@Bean
public RouterFunction<ServerResponse> notFound() {
    return RouterFunctions
      .route(GET("/statuses/not-found"),
         request -> ServerResponse.notFound().build());
}

3. Conclusion

When implementing an HTTP API, the framework gives a number of options to intelligently deal with the status codes we’re exposing back to the client.

This article should be a good starting point to explore these and understand how you can roll out expressive, friendly API, with clean, RESTful semantics.

Of course, the complete code examples used in this tutorial are available over on Github.