Skip to content

[FIX] Fix thread-safety race condition in GlobalExceptionHandler #212

Closed

Description

@aniebietafia

Problem

In GlobalExceptionHandler.java line 26, the exception handler class holds a single shared mutable instance field:

private final ErrorResponse errorResponse = new ErrorResponse();

Since Spring Boot instantiates @RestControllerAdvice classes as singleton beans, this single errorResponse instance is shared across all threads executing HTTP requests. When concurrent exceptions occur:

  • Thread A modifies errorResponse (e.g., sets message to "User not found").
  • Thread B concurrently modifies the same errorResponse (e.g., sets message to "Access denied").
  • Thread A returns the modified message from Thread B to client A, causing incorrect error reporting, information leaks, and incorrect HTTP response payloads under load.

(Note: While handleMaxUploadSizeExceededException creates a local instance, all other handlers mutate the shared instance).

Proposed Solution

Remove the class-level mutable errorResponse field. Instantiated local objects or builders must be created inside each @ExceptionHandler method.

User Stories

  • As a developer, I want global exception handling to be fully thread-safe so that the application does not mismatch error messages under concurrent load.
  • As an end user, I want to receive only the error message corresponding to my request, preventing me from seeing error details from other users.

Acceptance Criteria

  • The field private final ErrorResponse errorResponse is removed from GlobalExceptionHandler.java.
  • All @ExceptionHandler methods instantiate a new response object (or builder) locally within the method scope.
  • No class-level mutable state exists in GlobalExceptionHandler.java.
  • Integration tests running concurrent requests that trigger exceptions do not experience race conditions or cross-contamination of error messages.

Proposed Technical Details

// Before: Shared mutable instance
@RestControllerAdvice
public class GlobalExceptionHandler {
    private final ErrorResponse errorResponse = new ErrorResponse();

    @ExceptionHandler(NotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFoundException(NotFoundException ex) {
        errorResponse.setStatusCode(HttpStatus.NOT_FOUND.value());
        errorResponse.setMessage(ex.getMessage());
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse);
    }
}

// After: Thread-safe local instantiation (using unified ApiResponse)
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(NotFoundException.class)
    public ResponseEntity<ApiResponse<Void>> handleNotFoundException(NotFoundException ex, HttpServletRequest request) {
        ApiResponse<Void> response = ApiResponse.<Void>builder()
                .success(false)
                .statusCode(HttpStatus.NOT_FOUND.value())
                .message(ex.getMessage())
                .path(request.getRequestURI())
                .timestamp(Instant.now())
                .build();
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
    }
}

Tasks

  • Remove errorResponse field declaration.
  • Modify all @ExceptionHandler methods to declare HttpServletRequest as a parameter and construct responses locally.
  • Verify that mock controller tests simulating concurrent exceptions pass cleanly.

Open Questions / Considerations

  • Can we automate response wrapping to reduce boilerplate inside exception handlers? (See Issue 35 regarding global ResponseBodyAdvice).

Activity

  1. added
    bug
    enhancement
    on Jun 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    apibugcienhancementquestion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions