Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sprint Boot @Valid is not throwing the message as described

I am new to Spring Boot, and learning by doing it. I saw couple of videos and there they are showing to use @Valid keyword before the @RequestBody. But if i am doing so i am getting the error but not as expected.

I am hitting this URL with method = POST http://localhost:8080/users and i am getting this reponse. NO Error Message as defined.

{
    "timestamp": "2021-04-30T08:35:24.384+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "",
    "path": "/users"
}

sharing the controller file

User Controller.java

package xyz.fastview.testing.ui.controller;    
import javax.validation.Valid;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import xyz.fastview.testing.ui.mode.request.UserDetailRequestModel;
import xyz.fastview.testing.ui.model.response.UserRest;

@RestController
@RequestMapping("/users")
public class UserController {

    @PostMapping()
    public String createUser(@Valid @RequestBody UserDetailRequestModel userAccount) {
        return "Working Fine...!";
    }
}

UserDetailsRequestMode.java

package xyz.fastview.testing.ui.mode.request;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class UserDetailRequestModel {
    @NotNull(message = "firstName cannot be null")
    private String firstName;
    
    @NotNull(message = "lastName cannot be null")
    private String lastName;
    
    @NotNull(message = "email cannot be null")
    @Email(message = "email should be a proper email address")
    private String email;
    
    @NotNull
    @Size(min = 8, max = 20, message = "Password length can be 8 to 20 characters")
    private String password;

    // getters, setters
}
like image 648
abankitbaid Avatar asked Dec 05 '25 03:12

abankitbaid


1 Answers

Turn on custome messages for validator in your application.properties or application.yml. YAML for example:

server.error.include-message: always

Since version 2.3, Spring Boot hides the message field in the response to avoid leaking sensitive information.

like image 196
M. Dudek Avatar answered Dec 07 '25 19:12

M. Dudek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!