Skip to content

[REFACTOR] Standardize validation error response structure #213

Closed

Description

@aniebietafia

Problem

In GlobalExceptionHandler.java, the handler for field validation failures (MethodArgumentNotValidException) returns a custom flat Map<String, String> mapping fields directly to messages:

public ResponseEntity<@NonNull Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
    ...
    return ResponseEntity.badRequest().body(errors);
}

All other handlers return ErrorResponse. This inconsistency forces clients to implement dual error-parsing algorithms: one for validation responses (a plain JSON object of strings) and one for general application errors (a nested object containing statusCode and message).

Proposed Solution

Modify handleValidationExceptions to return the standardized ApiResponse<Void> structure. Map all field violations into a structured list of sub-errors within the errors property of the ApiResponse payload.

User Stories

  • As a client developer, I want validation errors to arrive in the same JSON structure as other errors, with a dedicated array of field-level errors, so I can cleanly iterate and render validation warnings next to UI input fields.

Acceptance Criteria

  • handleValidationExceptions returns ResponseEntity<ApiResponse<Void>>.
  • The response body contains success: false and statusCode: 400.
  • The errors field in the response is populated with a list of validation sub-errors, each containing:
    • field: The name of the invalid form parameter.
    • rejectedValue: The actual value submitted (for debugging, excluding sensitive fields like passwords).
    • message: The specific validation constraint failure message.
  • Plain map responses are completely eliminated from validation error payloads.

Proposed Technical Details

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiResponse<Void>> handleValidationExceptions(
        MethodArgumentNotValidException ex, HttpServletRequest request) {
        
    List<ApiResponse.ValidationError> validationErrors = ex.getBindingResult().getFieldErrors().stream()
            .map(fieldError -> new ApiResponse.ValidationError(
                    fieldError.getField(),
                    // Mask sensitive inputs like password fields
                    fieldError.getField().toLowerCase().contains("password") ? "[MASKED]" : fieldError.getRejectedValue(),
                    fieldError.getDefaultMessage()))
            .toList();

    ApiResponse<Void> response = ApiResponse.<Void>builder()
            .success(false)
            .statusCode(HttpStatus.BAD_REQUEST.value())
            .message("Validation failed")
            .errors(validationErrors)
            .path(request.getRequestURI())
            .timestamp(Instant.now())
            .build();

    return ResponseEntity.badRequest().body(response);
}

Tasks

  • Update ApiResponse to support a nested list of ValidationError objects.
  • Refactor the MethodArgumentNotValidException handler in GlobalExceptionHandler.java to return ApiResponse<Void>.
  • Mask validation values for fields containing the substring "password", "secret", or "token" to prevent accidental leak in logs or response payloads.
  • Update authorization and validator unit tests asserting validation payload structures.

Open Questions / Considerations

  • What happens if a constraint is a class-level validation error (like @PasswordMatches) instead of a field-level error? (See Issue 33 for dynamic resolution of class-level constraints).

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

    apibugcienhancementquestionsecurity

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions