Home > database >  Validation via @Pattern annotation
Validation via @Pattern annotation

Time:08-17

I want to validate input form Spring Boot application, and put message to the @Pattern annotation.

But when I run the application and try an invalid input I got only Bad request.

How can I show a meaningful message

{
  "timestamp": "2022-08-14T20:27:07.901 0000",
  "status": 400,
  "error": "Bad Request",
  "path": "/v1/list"
}

SearchCriteria.java

package com.event.model;

import lombok.Getter;
import lombok.Setter;

import javax.validation.constraints.Pattern;

@Getter
@Setter
public class SearchCriteria {


    @Pattern(regexp = "^\\d{4}\\-(0?[1-9]|1[012])\\-(0?[1-9]|[12][0-9]|3[01])$", message = "Invalid date format")
    private String from;

    @Pattern(regexp = "^\\d{4}\\-(0?[1-9]|1[012])\\-(0?[1-9]|[12][0-9]|3[01])$", message = "Invalid date format")
    private String to;

}

CodePudding user response:

To display a custom message you have to define a RestControllerAdvice that will intercept all your exeptions and return a custom message with ResponseEntity.

Map your validation exception in your service class with a controller custom exception:

try {
    // Your custom validation
} catch(ValidationException exception) {
    throw new BadRequest("Message", exception);
}

Define a RestControllerAdvice that will return a custom message type:

@ExceptionHandler(BadRequestException.class)
public ResponseEntity<Message> handleBadRequestException(BadRequestException exception) {
    var error = new Message(HttpStatus.BAD_REQUEST,
            LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
            exception.getMessage());

    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
}

When an exception is thrown the message 'Message' will be displayed.

How to set statuscode on postman throw exeption java

HTTP status code in case of failure scenario for a REST API which does SMTP connection test

  • Related