问题
I use Jackson to check and databind input JSON for a REST API, and I would like to log the error when the input doesn’t match a @Valid
constraint.
However, the exceptions are throwned as a Response
by the API but do not appear in Quarkus’ logs.
How do I log Jackson’s exceptions ?
回答1:
One has to create a handler for the Jackson exceptions, e.g. using ExceptionMapper.
The following example catches all exceptions of type JsonProcessingException (finer tuning is obviously possible), logs them as SEVERE
(using lombok’s @Log annotation) and returns a 400 Bad Request
Response
including the message. Note that the function has to be toResponse(Exception)
.
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.java.Log;
@Log
@Provider
public class MyJsonProcessingExceptionHandler implements ExceptionMapper<JsonProcessingException> {
@Override
public Response toResponse(JsonProcessingException exception) {
log.severe(exception.getMessage());
return Response.status(Response.Status.BAD_REQUEST).entity(exception.getMessage()).build();
}
}
Do not forget the @Provider
annotation so that the Exception handler acts as a filter on the REST API.
In principle other files of the project (including the controller) do not need to be modified, only this class in its own file.
来源:https://stackoverflow.com/questions/65206075/how-do-i-log-com-fasterxml-jackson-errors-with-quarkus