Spring Global Exception Handling
Example
java
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
ErrorResponse error = new ErrorResponse("NOT_FOUND", ex.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
}
// ...
}Guidelines
- Use
@RestControllerAdviceor@ControllerAdvicefor global error handling. - Return meaningful error messages and HTTP status codes.
- Define a standard error response structure.