Home > Net >  @Valid Springboot not sending message to postman response
@Valid Springboot not sending message to postman response

Time:08-25

i'm trying to use javax.validation on my Springboot project and the validations are not going to my postman response.

  • My Model:
@Lob
@Type(type = "org.hibernate.type.TextType")
@NotNull
@NotEmpty
@Column(name = "nome")
private String nome;
  • My Controller on the POST requisition:
@PostMapping(value = "/templates", produces = MediaType.APPLICATION_JSON_VALUE)
@ApiModelProperty("Cria um novo template")
public ResponseEntity<TemplateDTO> cadastraTemplate(@RequestBody @Valid TemplateDTO templateDTO, UriComponentsBuilder uriComponentsBuilder) {
        Template template = Template.desconvertId(templateDTO);
        templateRepository.save(template);
        URI uri = uriComponentsBuilder.path("template/{id}").buildAndExpand(template.getId()).toUri();
        return ResponseEntity.created(uri).body(new TemplateDTO(template));
    }
  • The @Valid is working, but is sending the message to my console, not when i send him on postman:

  • The Console message:

2022-08-24 15:44:13.285 ERROR 1668 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.validation.ConstraintViolationException: Validation failed for classes [com.ages.joinfut.Model.Template] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='não deve estar vazio', propertyPath=nome, rootBeanClass=class com.ages.joinfut.Model.Template, messageTemplate='{javax.validation.constraints.NotEmpty.message}'}
]] with root cause
  • On my Postman response:
{
    "timestamp": "2022-08-24T18:44:13.302 00:00",
    "status": 500,
    "error": "Internal Server Error",
    "path": "/example/templates"
}

Validation is working but why isn't going to response body on postman?

CodePudding user response:

When an exception is thrown, Spring has to determine how to convert a Java exception to an Http response. This is done by the ResponseEntityExceptionHandler. Your default ResponseEntityExceptionHandler is catching the ConstraintViolationException and converting it to a 500 and eating the exception message. Here's a guide on setting up custom exception handlers so you can populate the response message with relevant info.

  • Related