我正在使用 jersey-media-json-jackson-2.27,它具有内部 jackson.jaxrs.base,其中 JsonParseExceptionMapper 用于在收到无法解析的 JSON 时发送“400 Bad Request”。但我想要我自己的自定义映射器。
我已经创建了自己的自定义异常映射器。
我已经尝试设置注解@Priority(1),将其注册到我的 ResourceConfig 中,例如 register(ApplicationJsonExceptionMapper.class) 和 register(ApplicationJsonExceptionMapper.class, 1)。我也有注册(JacksonJaxbJsonProvider.class)。
package com.application.provider;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import com.fasterxml.jackson.core.JsonProcessingException;
@Provider
public class ApplicationJsonExceptionMapper implements
ExceptionMapper<JsonProcessingException> {
@Override
public Response toResponse(JsonProcessingException
jsonProcessingException) {
String responseMessage = "Invalid JSON";
return Response.status(Response.Status.BAD_REQUEST).entity(responseMessage).type("text/plain").build();
}
不幸的是,当我发送无效的 JSON 时,它仍然使用内置的 JsonParseExceptionMapper,您有什么想法可以尝试吗?
最佳答案
JsonProcessingException
是 JsonParseException
的父类(super class)。因此,为抛出 JsonParseException
调用 JsonParseException
的映射器是有道理的。如果您想覆盖它,请为 JsonParseException
创建您自己的映射器。您还需要为 JsonMappingException
创建一个,因为 Jackson 也为此创建了一个。
仅供引用,以便您了解如何选择映射器,这里引用了 JAX-RS 规范
When choosing an exception mapping provider to map an exception, an implementation MUST use the provider whose generic type is the nearest superclass of the exception.
关于java - 如何创建有效的自定义 JSON 解析异常映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54445762/