filip_j
filip_j

Reputation: 1225

Spring Boot validation error message not shown in response

I have following simple project to test spring boot validation. I am using Spring boot version 2.5.6

Validation dependency in pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

DTO object

import javax.validation.constraints.NotNull;

public class DepartmentDTO {

    @NotNull(message = "Department name can not be empty")
    private String name;

    // getter and setter
}

REST Controller

@RestController
public class DepartmentResource {

    @PostMapping("/departments")
    public ResponseEntity<DepartmentDTO> createDepartment(@Valid @RequestBody DepartmentDTO department) {
        return new ResponseEntity<>(department, HttpStatus.OK);
    }
}

When I fire a request with null name I get the error response, but the message is missing:

{
    "timestamp": "2021-12-03T09:13:52.729+00:00",
    "status": 400,
    "error": "Bad Request",
    "path": "/departments"
}

Upvotes: 14

Views: 9688

Answers (2)

Wasim
Wasim

Reputation: 1140

Add this in the application.yml

 server:
      error:
        include-stacktrace: never
        include-message: always
        include-binding-errors: always

Upvotes: 1

Scott Frederick
Scott Frederick

Reputation: 5155

Spring Boot limits the information included in the error response to reduce the risk of leaking sensitive information about the application to a client. You can explicitly enable additional information in the response by setting some properties in application.properties or application.yml.

server.error.include-binding-errors=always
server.error.include-message=always

Upvotes: 16

Related Questions