Skip to content
TheChatArchiveThe Chat Archive
o3-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

So it is possible I will have different path variables I will need to validate for UUID…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with gpt-4.1-mini-2025-04-14’s answer.
  1. User

    So it is possible I will have different path variables I will need to validate for UUID and each will have a different name lets say. So how can I write the custom validator and have the message specific to the requestparam

  2. Assistant

    Below are two idiomatic ways to get parameter-specific messages when the value that arrives in a path-variable / request-parameter is not a valid UUID.


    OPTION 1 – Let Spring’s built-in conversion fail and build the message in a single @ControllerAdvice

    1. Declare the parameters as UUID.
      Spring’s type converter will throw MethodArgumentTypeMismatchException whenever the incoming value cannot be parsed as a UUID.
    @GetMapping("/users/{userId}/orders/{orderId}")
    public OrderDto getOrder(
            @PathVariable UUID userId,
            @PathVariable UUID orderId,
            @RequestParam UUID correlationId) {
    
        /* controller logic */
    }
    
    1. Catch that exception and compose a message that contains the actual parameter name (ex.getName()).
    @ControllerAdvice
    public class UuidExceptionHandler {
    
        @ExceptionHandler(MethodArgumentTypeMismatchException.class)
        public ResponseEntity<ErrorResponse> handleUuidMismatch(MethodArgumentTypeMismatchException ex) {
    
            /* is this really a UUID problem? */
            if (ex.getRequiredType() == UUID.class) {
                String param     = ex.getName();          // e.g. “userId”, “orderId”
                String badValue  = String.valueOf(ex.getValue());
    
                String message = String.format(
                        "Parameter '%s' must be a valid UUID (received '%s').", param, badValue);
    
                return ResponseEntity
                        .badRequest()
                        .body(new ErrorResponse(message));
            }
    
            /* let some other @ExceptionHandler deal with it */
            throw ex;
        }
    }
    

    Pros
    • Zero custom annotations or validators
    • One place to format the error for any UUID parameter (path-vars or request-params)
    • You automatically get HTTP 400


    OPTION 2 – Custom @ValidUuid annotation with per-parameter message

    If you prefer Bean-Validation style (@Valid, @Pattern, …) you can write one validator and override the message at every usage.

    1. Annotation
    @Target({ ElementType.PARAMETER, ElementType.FIELD })
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = UuidValidator.class)
    public @interface ValidUuid {
    
        String message() default "Invalid UUID value";
    
        Class<?>[] groups()   default {};
        Class<? extends Payload>[] payload() default {};
    }
    
    1. Validator
    public class UuidValidator implements ConstraintValidator<ValidUuid, String> {
    
        @Override
        public boolean isValid(String value, ConstraintValidatorContext ctx) {
            if (value == null) return true;   // leave @NotNull to another annotation
            try {
                UUID.fromString(value);
                return true;
            } catch (IllegalArgumentException ex) {
                return false;
            }
        }
    }
    
    1. Use it with a custom message per parameter:
    @GetMapping("/users/{userId}/orders/{orderId}")
    public OrderDto getOrder(
            @PathVariable
            @ValidUuid(message = "Path variable 'userId' must be a valid UUID")
            String userId,
    
            @PathVariable
            @ValidUuid(message = "Path variable 'orderId' must be a valid UUID")
            String orderId,
    
            @RequestParam
            @ValidUuid(message = "Query parameter 'correlationId' must be a valid UUID")
            String correlationId) {
    
        /* controller logic */
    }
    

    Any violation triggers ConstraintViolationException, which you can collect in a normal @ExceptionHandler for Java-Bean-Validation errors.

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<ErrorResponse> handleValidation(ConstraintViolationException ex) {
        String combined = ex.getConstraintViolations()
                            .stream()
                            .map(ConstraintViolation::getMessage)
                            .collect(Collectors.joining("; "));
        return ResponseEntity.badRequest().body(new ErrorResponse(combined));
    }
    

    Pros
    • Flexible, reusable annotation
    • Message can be fully customised where you annotate
    • Works for fields in DTOs as well, not just controller parameters


    Choose the approach that matches your code style:

    • Need just UUID parameters on controllers? Option 1 is minimal and leverages what Spring already gives you.
    • Need Bean-Validation style and per-usage messages? Option 2 is equally concise once the annotation exists.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.