Spring Boot Exception Handling Annotations
In Spring Boot, exception handling is an important feature that allows developers to manage runtime errors in a clean and consistent way. Spring Boot provides several annotations to handle exceptions at different levels, such as method-level, controller-level, and global level.
1. @ExceptionHandler
The @ExceptionHandler annotation is used to handle specific exceptions in a controller. You can define a method annotated with @ExceptionHandler to manage exceptions thrown by request handling methods.
@RestController
public class MyController {
@GetMapping("/example")
public String example() {
if (true) {
throw new RuntimeException("Something went wrong!");
}
return "Success";
}
@ExceptionHandler(RuntimeException.class)
public ResponseEntity handleRuntimeException(RuntimeException ex) {
return new ResponseEntity<>("Error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Key Points:
- Handles exceptions for the methods in the same controller.
- You can specify one or more exception classes in the annotation.
- Returns custom error response to the client.
2. @ControllerAdvice
The @ControllerAdvice annotation allows you to handle exceptions globally for all controllers. It acts as an interceptor of exceptions thrown by methods annotated with @RequestMapping or other request-handling annotations.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity handleRuntimeException(RuntimeException ex) {
return new ResponseEntity<>("Global Error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(NullPointerException.class)
public ResponseEntity handleNullPointerException(NullPointerException ex) {
return new ResponseEntity<>("Null Pointer Error: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
}
}
Key Points:
- Handles exceptions globally across all controllers.
- Helps maintain cleaner controller code.
- Can define multiple
@ExceptionHandlermethods for different exception types.
3. @ResponseStatus
The @ResponseStatus annotation can be used to define the HTTP status code for a specific exception. This is useful for returning proper HTTP responses without manually creating a ResponseEntity.
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
@RestController
public class MyController {
@GetMapping("/resource")
public String getResource() {
throw new ResourceNotFoundException("Resource not found!");
}
}
Key Points:
- Automatically sets the HTTP status code for the exception.
- Can be used on custom exception classes.
- Reduces boilerplate code for exception responses.
4. @ResponseBody
The @ResponseBody annotation can be used in combination with @ExceptionHandler or @ControllerAdvice to return JSON or XML responses instead of a view.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public Map handleRuntimeException(RuntimeException ex) {
Map response = new HashMap<>();
response.put("error", ex.getMessage());
response.put("status", "500");
return response;
}
}
Key Points:
- Ensures the exception response is sent as JSON/XML.
- Commonly used in REST APIs.
Summary
Spring Boot exception handling annotations provide a structured way to manage errors:
- @ExceptionHandler: Handles exceptions at the controller level.
- @ControllerAdvice: Handles exceptions globally across controllers.
- @ResponseStatus: Defines HTTP status for custom exceptions.
- @ResponseBody: Sends structured responses (JSON/XML) for exceptions.
Using these annotations together allows developers to create robust and maintainable error-handling strategies in Spring Boot applications.