我该如何在Quarkus中记录com.fasterxml.jackson错误? [英] How do I log com.fasterxml.jackson errors with Quarkus?
问题描述
我使用Jackson来检查和绑定REST API的输入JSON,并在输入与@Valid
约束不匹配时记录错误.
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.
但是,异常由API作为Response
抛出,但未出现在Quarkus的日志中.
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 ?
推荐答案
必须为Jackson异常创建处理程序,例如使用 ExceptionMapper
.
One has to create a handler for the Jackson exceptions, e.g. using ExceptionMapper
.
以下示例捕获了 lombok的@Log
注释),并返回包含消息的400 Bad Request
Response
.请注意,该功能必须为toResponse(Exception)
.
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();
}
}
请不要忘记@Provider
批注,以便Exception处理程序充当REST API的筛选器.
原则上,无需修改项目的其他文件(包括控制器),只需在其自己的文件中修改此类.
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.
这篇关于我该如何在Quarkus中记录com.fasterxml.jackson错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!