Mister_L
Mister_L

Reputation: 2611

spring boot custom validation message not shown

I have an endpoint that accepts query parameters bound to a class GetParams:

public class GetParams{
    @Min(value = 0, message = "OFFSET_INVALID")
    private Integer offset;

    @Min(value = 0, message = "LIMIT_INVALID")
    private int limit;

    public GetParams() {
        this.offset = 0;
        this.limit = 100;
    }

    public int getOffset() {
        return offset;
    }

    public int getLimit() {
        return limit;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

}

This is the endpoint in my controller:

@GetMapping(value = "/applications")
public ResponseEntity<Data> getApplications( @Validated GetParams parameters) { ... }

When I send a GET request that violates one of the constraints, for example:

GET /applications?offset=-20&limit=100

The framework returns a 400, but without my messages, and in fact without a response body and without a stack trace printed into the console! When the query params are valid, the result is valid as well. Why is this?

Thanks.

Upvotes: 1

Views: 1166

Answers (3)

lukeoldsword
lukeoldsword

Reputation: 11

From root path you can set 'include binding errors' in "resources/application.properties" to "always". Same goes for 'message' as well.

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

Upvotes: 1

user404
user404

Reputation: 2028

For a GET request you can't validate the request-params binding with object like you did above. You have to validate each param by themselves separately like this:

public ResponseEntity<Data> getApplications(@RequestParam @Min(1) @Max(value=7, message="you custom message") Integer offset,  @RequestParam @Min(3) Integer params2, ... )
{
        //your code/logic
}

You can validate that way only for POST and other requests with @RequestBody which have body in their requests.

Upvotes: 1

padmanabhanm
padmanabhanm

Reputation: 315

Request parameters are to mapped using @RequestParam.

Try

@GetMapping(value = "/applications")
public ResponseEntity<Data> getApplications( @Validated @ReqeustParam @Min(value = 0, message = "OFFSET_INVALID") Integer offset) { ... }`

Upvotes: 0

Related Questions