Skip to content

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 @RestControllerAdvice or @ControllerAdvice for global error handling.
  • Return meaningful error messages and HTTP status codes.
  • Define a standard error response structure.

References

Copyright © MSG Systems Romania AI Labs