The ability to correctly handle errors in APIs while providing meaningful error messages is a very desirable feature that helps the API client to respond to issues appropriately. In this shot, we will go over how to do proper exception handling with Spring Boot, an open-source Java-framework for building micro-services.
Let’s look at two Spring annotations that we will be use to handle exceptions:
@ExceptionHandler
@ControllerAdvice
The @ExceptionHandler
is an annotation used to handle exceptions thrown during the execution of handlers and send custom responses to the client.
The most common way to use @ExceptionHandler
is on methods of @ControllerAdvice
classes so that the exception handling is applied globally.
The @ControllerAdvice
annotation handles exceptions globally – it allows you to use the same ExceptionHandler
for multiple controllers. This way, we can define how to treat an exception in just one place because this handler will be called whenever the exception is thrown from classes that are covered by ControllerAdvice
.
Let’s use @ExceptionHandler
and @ControllerAdvice
to define a central point for treating exceptions and wrapping them up in a class.
We first define a class that will handle the exceptions. Let’s call it ExampleExceptionHandler
.
Next, we will define a custom exception class called ExampleException
:
public class ExampleException extends RuntimeException {
public ExampleException(String message) {
super(message);
}
}
It’s a good practice to name your exceptions specifically. We are only using the names
ExampleException
andExampleExceptionHandler
for illustration.
Finally, we can handle our new exception:
@ControllerAdvice
public class ExampleExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(ExampleException.class)
protected ResponseEntity<Object> exception(ExampleException exception) {
String errorMsg = "Example error message";
return new ResponseEntity<>(errorMsg, HttpStatus.BAD_REQUEST);
}
// more exception handlers...
}
You can also override the existing exception handlers. Spring Boot’s built-in exception class ResponseEntityExceptionHandler
has multiple methods that you can override to customize the exception handling further.
We extend the ExampleExceptionHandler
class with the ResponseEntityExceptionHandler
class, and override the handleHttpMessageNotReadable()
method:
@ControllerAdvice
public class ExampleExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String errorMsg = "Example error message";
return new ResponseEntity<>(errorMsg, HttpStatus.BAD_REQUEST);
}
// more exception handlers ...
}
Free Resources