Home > other >  How to display validation error messages and codes in a Spring WebFlux Rest API
How to display validation error messages and codes in a Spring WebFlux Rest API

Time:05-05

I'm using Spring Web MVC in a Reactive SpringBoot Application, and wrote a custom validator. In case of a validation error, a 400 response code is used, which is fine, but then AbstractErrorWebExceptionHandler catches this and spits out

{
    "timestamp": 1651678946524,
    "path": "/signup",
    "status": 400,
    "error": "Bad Request",
    "requestId": "0f61cb96-1"
}

which is not very useful to the client. How can I display the error messages and codes? I know they are available, because they are logged:

DEBUG 32475 --- [     parallel-1] a.w.r.e.AbstractErrorWebExceptionHandler : [0f61cb96-1] Resolved [WebExchangeBindException: Validation failed for argument at index 0 in method: public reactor.core.publisher.Mono<...with 1 error(s): [Field error in object 'userSignup' on field 'username': rejected value [matilda0]; codes [username.exists.userSignup.username,username.exists.username,username.exists.java.lang.String,username.exists]; arguments []; default message [null]] ] for HTTP POST /signup

Any help would be appreciated, thank you.

CodePudding user response:

This is what I did:

private void validate(SomeEntity someEntity) {
    Errors errors = new BeanPropertyBindingResult(someEntity, "SomeEntity");
    validator.validate(someEntity, errors);
    if (errors.hasErrors()) {
        throw new ServerWebInputException(errors.toString());
    }
}

Validator is injected:

private final Validator validator;
private final SomeEntityDao dao;

public SomeEntityHandler(
        Validator validator,
        SomeEntityDao dao
) {
    this.validator = validator;
    this.dao = dao;
}

Project: WebFluxR2dbc

CodePudding user response:

Adding

server.error.include-binding-errors=ALWAYS

in application.properties seems to fix it, although it still doesn't look up the message code properly. To actually get the error message itself to appear in the response, I had to wire in a MessageSourceAccessor in my Validator and use that as the default message!

errors.rejectValue("username","username.exists",msgs.getMessage("username.exists"))

So I must still be missing something, but this will work for now.

  • Related