efthimisVaf
efthimisVaf

Reputation: 51

Spring Boot Rest Api not displaying validation message

I am developing a small REST API by using Spring Boot. I am using validation annotations in my entity class:

@NotEmpty(message="Please enter a first name")
private String firstName; 

Here is my controller and service:

@RestController
public class CustomerController {

    @Autowired
    private CustomerService userService;

    @PostMapping("/customer")
    @ResponseStatus(HttpStatus.CREATED)
    public Customer postUser (@RequestBody @Valid Customer customer){

      return userService.save(customer);

    } 
}
public class CustomerService {

    @Autowired
    private CustomerRepository repository;

    @Transactional
    public Customer save ( Customer customer){

        return repository.save(customer);
    }
}

Here is the response I get when I try to send a JSON with an empty firstName Value:

{
    "timestamp": "2020-06-08T08:40:08.660+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "",
    "path": "/MVCwebshop/customer"
}

As you can see, the "message" field is empty in the JSON I get. This is also happening when I try to use the default messages. How can I fix this?

Upvotes: 5

Views: 6940

Answers (3)

Omkar Mahadeshwar
Omkar Mahadeshwar

Reputation: 41

Along with server.error.include-message=always as mentioned above, you can also add server.error.include-binding-errors=always to application.properties. This will list all the binding errors, along with the specific message

Upvotes: 4

Rebai Ahmed
Rebai Ahmed

Reputation: 1600

You can add the validation query :

@NotEmpty(message="Please enter a first name")
@Size(min= 1, max = 50, message="actor.firstName.size")
private String firstName; 

Upvotes: 0

Lars Michaelis
Lars Michaelis

Reputation: 569

In case of using Spring Boot 2.3.0.RELEASE you have to set

server.error.include-message=always

in your application.properties (or yaml).

See here

Upvotes: 10

Related Questions