How do I log com.fasterxml.jackson errors with Quarkus?

走远了吗. 提交于 2021-02-05 09:27:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!