Still Writing try-catch Blocks in Every Controller?
Let’s talk about error handling in Java web apps.
The classic, traditional way involves littering your controller methods with try-catch blocks. One for each endpoint. It works. But it is repetitive, verbose, and mixes your business logic with error-handling logic. It simply does not scale well.
There is a much cleaner way in Spring Boot. The framework gives us powerful tools for centralized exception handling.
Enter @ControllerAdvice and @ExceptionHandler.
The Concept
Instead of catching exceptions inside every method, you create a single, global “advisor” class. This class listens for specific exceptions thrown from anywhere in your application (like UserNotFoundException or ValidationException).
When it “hears” an exception, it catches it and crafts the perfect HTTP error response (like a 404 Not Found or a 400 Bad Request).
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) {
ErrorResponse error = new ErrorResponse("NOT_FOUND", ex.getMessage());
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
}
Why is this a superior approach?
1. Clean Controllers: Your controller methods become incredibly clean. They focus only on the “happy path,” the actual business logic.
2. Separation of Concerns: Error-handling logic is neatly isolated in one place, making it much easier to manage and maintain.
3. Consistency: You guarantee that the same type of error will always produce the same, consistent JSON error response across your entire API.
It is a huge step up in terms of design and architecture. It is about moving from defensive coding in every method to a robust, declarative error-handling strategy.