2

I want to set custom error Message for Unrecognized field and others errors with request body. I tried ExceptionMapper but it dont work :/ Using quarkus and Jackson

public class ReqDTO {
    private String a;
}

when send request:

{
    "a": "a"
}

its look good. But when send:

{
    "a": "a",
    "b": "b"
}

have error response:

Unrecognized field "b"; (class ReqDTO), not marked as ignorable

Want customize this message and other bad json body (like too much fields) to own message like "BAD_JSON_SCHEMA".

Tried

@Provider
public class ExHandler implements ExceptionMapper<JsonMappingException>{

    public Respone toResponse(JsonMappingException e) { 
        //response bad field impl
    }
}

But its not work. Looks like a json handle exception faster. Tried with "Exception", "JsonParseException" but nothing changed :/

@Path("/")
public class Controller {
    @Post
    @Consume(APPLICATION_JSON)
    @Produces(TEXT_PLAIN)
    public Response getA(@Valid ReqDTO reqDTO){
        //logic
    }
}

@Edit

Found something like DeserializationProblemHandler but dont know how change message for handleUnknownProperty :/

KanekiSenpai
  • 122
  • 10
  • What have you done so far? It would be great to show some code samples, so others can reproduce the issues you have. – Ghokun Sep 23 '20 at 09:53
  • You can try registering a simple module with the proper handler. An example can be found here: https://stackoverflow.com/questions/48773728/configure-a-jacksons-deserializationproblemhandler-in-spring-environment . This is spring configuration though, you have to modify it for quarkus. – Ghokun Sep 23 '20 at 11:54

1 Answers1

4
@Singleton
RegisterCustomModuleCustomizer implements ObjectMapperCustomizer {

    public void customize(ObjectMapper mapper){
        mapper.addHandler(new DeserializationProblemHandler(){
            @SneakyThrows
            @Override
            public boolean handleUnknownProperty(...... params){
                throw new ApplicationException("ERRO_BODY_MESS");
            }
        }
    }
}

@Provider
public class ExHandler implements ExceptionMapper<ApplicationException>{

    public Respone toResponse(ApplicationException ex) { 
        return Response.status(BAD_REQUEST).entity(ex.getMessage()).build();
    }
}
KanekiSenpai
  • 122
  • 10