How to Handle Exceptions in Spring Boot: Simple Guide
@ControllerAdvice and defining methods with @ExceptionHandler to catch specific exceptions. This approach centralizes error handling and returns meaningful responses to clients.Why This Happens
When an exception occurs in a Spring Boot controller and is not caught, the server returns a generic error response, often a 500 Internal Server Error. This happens because the application does not have a defined way to handle unexpected errors gracefully.
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SampleController { @GetMapping("/error") public String error() { throw new RuntimeException("Something went wrong"); } }
The Fix
To fix this, create a class annotated with @ControllerAdvice and add methods annotated with @ExceptionHandler to catch exceptions and return custom responses. This way, you control what the client sees when errors happen.
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(RuntimeException.class) public ResponseEntity<String> handleRuntimeException(RuntimeException ex) { return new ResponseEntity<>("Custom error message: " + ex.getMessage(), HttpStatus.BAD_REQUEST); } }
Prevention
Always anticipate possible errors and handle them centrally using @ControllerAdvice. Define specific handlers for different exception types to provide clear feedback. Avoid catching exceptions only in controllers to keep code clean and maintainable.
Use meaningful HTTP status codes and messages. Consider logging exceptions for debugging. Use validation annotations to prevent invalid input that causes exceptions.
Related Errors
Common related errors include:
- 404 Not Found: Happens when a requested resource does not exist. Handle with
@ExceptionHandler(org.springframework.web.servlet.NoHandlerFoundException.class). - MethodArgumentNotValidException: Occurs when validation on request data fails. Handle to return validation error details.
- AccessDeniedException: Happens when user lacks permission. Handle to return 403 Forbidden with a message.