Class GlobalExceptionHandler

java.lang.Object
io.github.pasinduog.exception.GlobalExceptionHandler

@ConditionalOnProperty(prefix="api-response", name="enabled", havingValue="true", matchIfMissing=true) @RestControllerAdvice public class GlobalExceptionHandler extends Object
Global Exception Handler for the application.

This class intercepts exceptions thrown by any controller across the application and transforms them into a standard ProblemDetail format (RFC 9457 / 7807). This ensures a consistent error response structure for API clients.

Automatically registered via Spring Boot autoconfiguration when the library is on the classpath. No manual configuration required.

New in v2.0.0: All error responses now include a traceId from SLF4J MDC for distributed tracing and log correlation. If no traceId exists in MDC, a random UUID is generated automatically.

Handled Exception Types:

  • Exception - Catch-all for unexpected errors (HTTP 500)
  • MethodArgumentNotValidException - Bean validation failures (HTTP 400)
  • MethodArgumentTypeMismatchException - Type conversion errors (HTTP 400)
  • HttpMessageNotReadableException - Malformed JSON body (HTTP 400)
  • MissingServletRequestParameterException - Missing required parameters (HTTP 400)
  • NoResourceFoundException - 404 Not Found for endpoints/resources (HTTP 404)
  • HttpRequestMethodNotSupportedException - Invalid HTTP method (HTTP 405)
  • HttpMediaTypeNotSupportedException - Unsupported Content-Type (HTTP 415)
  • NullPointerException - Null pointer errors (HTTP 500)
  • ApiException - Custom business logic exceptions (custom HTTP status)

Response Format:

All responses follow RFC 7807 ProblemDetail structure with additional properties:

  • type - A URI reference identifying the problem type
  • title - A short, human-readable summary of the problem type
  • status - The HTTP status code
  • detail - A human-readable explanation of the error
  • instance - A URI reference identifying the specific occurrence
  • traceId - UUID for request tracing and log correlation (custom property)
  • timestamp - ISO-8601 timestamp when the error occurred (custom property)
  • errors - Field-level validation errors map (for validation failures only)
Since:
1.2.0
Version:
2.0.1
Author:
Pasindu OG
See Also:
  • Constructor Details

    • GlobalExceptionHandler

      public GlobalExceptionHandler()
      Default constructor for GlobalExceptionHandler.

      This constructor is automatically invoked by Spring's dependency injection container when registering this exception handler as a bean.

  • Method Details

    • handleAllExceptions

      @ExceptionHandler(java.lang.Exception.class) public org.springframework.http.ProblemDetail handleAllExceptions(Exception ex)
      Handles all unexpected exceptions (catch-all handler).

      This method acts as a safety net for any error not explicitly handled by other methods. It returns a generic 500 Internal Server Error to avoid leaking sensitive stack traces to the client, while logging the full error details for debugging.

      The response includes a traceId from SLF4J MDC (or a generated UUID) and a timestamp to help with error tracking and log correlation.

      Parameters:
      ex - The exception that was thrown.
      Returns:
      A ProblemDetail with HTTP 500 status, traceId, timestamp, and a generic error message.
    • handleValidationExceptions

      @ExceptionHandler(org.springframework.web.bind.MethodArgumentNotValidException.class) public org.springframework.http.ProblemDetail handleValidationExceptions(org.springframework.web.bind.MethodArgumentNotValidException ex)
      Handles bean validation errors (e.g., @NotNull, @Size failures).

      Triggers when a RequestBody fails validation. It collects all field-level errors and returns them in a map under the "errors" property. If a field has multiple errors, they are joined by a semicolon.

      The response includes a traceId from SLF4J MDC (or a generated UUID), timestamp, and a detailed map of field validation errors.

      Parameters:
      ex - The validation exception containing the list of field errors.
      Returns:
      A ProblemDetail with HTTP 400 status, traceId, timestamp, and a map of validation errors.
    • handleMethodArgumentTypeMismatchException

      @ExceptionHandler(org.springframework.web.method.annotation.MethodArgumentTypeMismatchException.class) public org.springframework.http.ProblemDetail handleMethodArgumentTypeMismatchException(org.springframework.web.method.annotation.MethodArgumentTypeMismatchException ex)
      Handles type mismatch errors for method arguments.

      This occurs when a request parameter cannot be converted to the expected type, such as passing a string where an integer is required.

      The response includes a consistent traceId (from MDC or generated) and timestamp to help with debugging and log correlation.

      Parameters:
      ex - The type mismatch exception.
      Returns:
      A ProblemDetail with HTTP 400 status, traceId, timestamp, and a descriptive error message.
    • handleHttpMessageNotReadableException

      @ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class) public org.springframework.http.ProblemDetail handleHttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException ex)
      Handles malformed JSON errors.

      Triggered when the request body is invalid JSON (e.g., missing commas, brackets, or wrong types).

      The response includes a consistent traceId (from MDC or generated) and timestamp for debugging and log correlation.

      Parameters:
      ex - The exception thrown when JSON parsing fails.
      Returns:
      A ProblemDetail with HTTP 400 status, traceId, and timestamp.
    • handleMissingServletRequestParameterException

      @ExceptionHandler(org.springframework.web.bind.MissingServletRequestParameterException.class) public org.springframework.http.ProblemDetail handleMissingServletRequestParameterException(org.springframework.web.bind.MissingServletRequestParameterException ex)
      Handles missing required parameters.

      Triggered when a required @RequestParam is missing from the request URL.

      The response includes a traceId from SLF4J MDC (or a generated UUID) and timestamp for debugging and log correlation.

      Parameters:
      ex - The exception containing the missing parameter name.
      Returns:
      A ProblemDetail with HTTP 400 status, traceId, and timestamp.
    • handleNoResourceFoundException

      @ExceptionHandler(org.springframework.web.servlet.resource.NoResourceFoundException.class) public org.springframework.http.ProblemDetail handleNoResourceFoundException(org.springframework.web.servlet.resource.NoResourceFoundException ex)
      Handles 404 Not Found errors for static resources and missing endpoints (Spring Boot 3.2+).

      This eliminates the need for configuring spring.mvc.throw-exception-if-no-handler-found. It catches the exception thrown when no controller or static resource is found.

      The response includes a consistent traceId (from MDC or generated) and timestamp for debugging and log correlation.

      Parameters:
      ex - The exception containing the requested resource path.
      Returns:
      A ProblemDetail with HTTP 404 status, traceId, and timestamp.
    • handleHttpRequestMethodNotSupportedException

      @ExceptionHandler(org.springframework.web.HttpRequestMethodNotSupportedException.class) public org.springframework.http.ProblemDetail handleHttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException ex)
      Handles unsupported HTTP methods (405).

      Triggered when a user sends a request with a method (e.g., POST) that is not supported by the endpoint (e.g., it only expects GET).

      The response includes a consistent traceId (from MDC or generated) and timestamp for debugging and log correlation.

      Parameters:
      ex - The exception containing the supported methods.
      Returns:
      A ProblemDetail with HTTP 405 status, traceId, and timestamp.
    • handleHttpMediaTypeNotSupportedException

      @ExceptionHandler(org.springframework.web.HttpMediaTypeNotSupportedException.class) public org.springframework.http.ProblemDetail handleHttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException ex)
      Handles unsupported media types (415).

      Triggered when the client sends a Content-Type (e.g., application/xml) that the server cannot process.

      The response includes a traceId from SLF4J MDC (or a generated UUID) and timestamp for debugging and log correlation.

      Parameters:
      ex - The exception containing the supported media types.
      Returns:
      A ProblemDetail with HTTP 415 status, traceId, and timestamp.
    • handleNullPointerExceptions

      @ExceptionHandler(java.lang.NullPointerException.class) public org.springframework.http.ProblemDetail handleNullPointerExceptions(NullPointerException ex)
      Handles NullPointerExceptions explicitly.

      While strictly not necessary (as the catch-all handler covers this), having a specific handler allows for distinct logging or custom messaging for NPEs if required in the future.

      The response includes a consistent traceId (from MDC or generated) and timestamp for debugging and log correlation.

      Parameters:
      ex - The NullPointerException that was thrown.
      Returns:
      A ProblemDetail with HTTP 500 status, traceId, and timestamp.
    • handleApiException

      @ExceptionHandler(ApiException.class) public org.springframework.http.ProblemDetail handleApiException(ApiException ex)
      Handles all custom exceptions that extend ApiException.

      This method dynamically extracts the HTTP status and message from the thrown exception, providing a standardized RFC 7807 response for any domain-specific error created by the library user.

      The response includes a consistent traceId (from MDC or generated) and timestamp for debugging and log correlation across distributed systems.

      Parameters:
      ex - The custom API exception instance.
      Returns:
      A ProblemDetail with the status and message defined in the exception, plus traceId and timestamp.