Did you know about @ControllAdvice in Spring Boot?
2 min readOct 6, 2024
What is @ControllerAdvice
?
In a typical Spring application, you may have multiple controllers that handle various HTTP requests. Sometimes, errors or exceptions occur, and you need to return meaningful error messages or status codes. Instead of repeating exception handling logic across all your controllers, you can centralize this logic using @ControllerAdvice
.
@ControllerAdvice
allows you to handle exceptions globally, across multiple controllers, from a single place.
Example
Let’s say you have a simple REST controller that throws exceptions when something goes wrong:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public String getUserById(@PathVariable String id) {
if ("123".equals(id)) {
return "User found: John Doe";
} else {
throw new UserNotFoundException("User not found with id: " + id);
}
}
}