Reactive Programming in Spring WebFlux Series - III
Error Handling and Debugging
Error Handling
Error handling in reactive programming is different from traditional synchronous programming due to the asynchronous nature of reactive streams. In Reactor, errors are handled in various ways:
1. onErrorReturn
This operator allows returning a default value when an error occurs. Example:
Flux<String> flux = Flux.just("A", "B", "C")
.concatWith(Flux.error(new RuntimeException("Exception occurred")))
.onErrorReturn("Default");
flux.subscribe(System.out::println);
In this example, when an error occurs, the default value "Default" is returned.
2. onErrorResume
This operator allows switching to another Publisher when an error occurs. Example:
Flux<String> flux = Flux.just("A", "B", "C")
.concatWith(Flux.error(new RuntimeException("Exception occurred")))
.onErrorResume(e -> {
System.out.println("Error: " + e.getMessage());
return Flux.just("D", "E");
});
flux.subscribe(System.out::println);
Here, when an error occurs, it switches to another Flux sequence to continue processing new data.
3. onErrorMap
This operator allows converting an error into a different type of error. Example:
Flux<String> flux = Flux.just("A", "B", "C")
.concatWith(Flux.error(new RuntimeException("Exception occurred")))
.onErrorMap(e -> new CustomException("Custom message", e));
flux.subscribe(System.out::println, e -> System.out.println("Error: " + e.getMessage()));
In this case, a RuntimeException is converted into a custom CustomException.
Global Error Handling in WebFlux
In addition to handling errors in streams, Spring WebFlux also allows defining a global error handler for managing errors across the application.
1. Defining a Custom Exception Class
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
2. Creating an Exception Handler
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.function.server.ServerResponse.BodyBuilder;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;
@Component
@Order(-2)
public class GlobalErrorHandler implements WebExceptionHandler {
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
BodyBuilder response = ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
.contentType(MediaType.APPLICATION_JSON);
if (ex instanceof CustomException) {
response = ServerResponse.status(HttpStatus.BAD_REQUEST);
}
return response.bodyValue(new ErrorResponse(ex.getMessage()))
.flatMap(resp -> resp.writeTo(exchange, new Context()));
}
private static class ErrorResponse {
private final String message;
public ErrorResponse(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
}
Debugging Reactive Applications
Debugging reactive applications can be more challenging than debugging traditional synchronous applications. Here are some debugging techniques:
1. Using the log Operator
Reactor provides the log operator to output log information for each step. Example:
Flux<String> flux = Flux.just("A", "B", "C")
.concatWith(Flux.error(new RuntimeException("Exception occurred")))
.log();
flux.subscribe(System.out::println);
2. Breakpoint Debugging
Setting breakpoints in an IDE allows you to step through the execution. Be mindful of thread switching and asynchronous execution details when debugging reactive code.
3. Using Reactor Debugger
Reactor provides a special debug tool Hooks.onOperatorDebug to help understand and debug operations in reactive streams.
Hooks.onOperatorDebug();
Flux<String> flux = Flux.just("A", "B", "C")
.concatWith(Flux.error(new RuntimeException("Exception occurred")));
flux.subscribe(System.out::println);
Conclusion
In this article, we explored how to handle errors and debug reactive applications in Spring WebFlux, providing techniques for both stream-level and global error handling.