Handling Errors in One Place
@ControllerAdvice is a class that handles errors for every controller at once. One handler in that class answers one kind of error for the whole app.
Mark the advice class
This class carries @ControllerAdvice. Its methods handle errors for every controller.
@ControllerAdvice
public class GlobalExceptionHandler {
}Handle a bad title
This method answers IllegalArgumentException with status 400. The body carries the error message.
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleBadTitle(IllegalArgumentException error) {
return ResponseEntity.badRequest().body(error.getMessage());
}Example
package com.example.demo;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleBadTitle(IllegalArgumentException error) {
return ResponseEntity.badRequest().body(error.getMessage());
}
}
@RestController
class TaskController {
@PostMapping("/tasks")
public String addTask(@RequestBody TaskForm form) {
if (form.title() == null || form.title().isBlank()) {
throw new IllegalArgumentException("Task title must not be empty");
}
return "Saved";
}
record TaskForm(String title, boolean done) {
}
}
Key points
- @ControllerAdvice marks a class as a shared error handler.
- @ExceptionHandler marks a method that answers one error type.
- The handler runs when a controller throws that error.
- One handler can serve every controller in the app.
- The handler returns the answer the client receives.
In this example, the class carries @ControllerAdvice, so it handles errors for every controller. The method carries @ExceptionHandler for IllegalArgumentException. When a controller throws that error, the method runs. It builds a 400 answer with the error message as the body. The client receives status 400 and the text Task title must not be empty. A small controller in the example throws the error when a title is blank.
Note
A handler answers only the error type it names.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @ControllerAdvice do?