Hi everyone,
I wanted to share a quick tip for handling errors in a more structured way in Spring Boot applications using @ControllerAdvice and @ExceptionHandler.
Problem: In a typical Spring Boot REST API, we may have multiple exceptions thrown across different controllers. Manually handling them can lead to duplicated code and inconsistent responses.
Solution: @ControllerAdvice provides a global error handling mechanism, allowing you to centralize exception handling logic. Here's an example:
`@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleResourceNotFoundException(ResourceNotFoundException ex) {
ErrorResponse errorResponse = new ErrorResponse("RESOURCE_NOT_FOUND", ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
ErrorResponse errorResponse = new ErrorResponse("INTERNAL_SERVER_ERROR", "An unexpected error occurred");
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
ErrorResponse Class:
public class ErrorResponse {
private String code;
private String message;
public ErrorResponse(String code, String message) {
this.code = code;
this.message = message;
}
// Getters and Setters
}`
Key Takeaway: By using @ControllerAdvice, we can centralize error handling, making the code cleaner, more maintainable, and ensuring consistent error responses across the application.
Iād love to know if anyone has other tips for simplifying error handling or improving best practices in Spring Boot!
Cheers!
Top comments (0)