如何在Jersey JAX-RS中处理无效的数据类型错误

问题描述 投票:0回答:1

我正在研究JAX-RS API,用户将以下JSON有效负载发送到我的API:

{
    "text": "test search",
    "count": "myvalue"
}

如上所述,count在POJO SearchDetailsInfo.java中的类型为Integer,但是用户在将数据发布到此API时会在其中发送一些垃圾字符串。

请在下面找到我的控制器方法:

@POST
@Path("/myview")
@Produces(MediaType.APPLICATION_JSON)
public OrderedJSONObject getCatalogView(SearchDetailsInfo criteria,
                @Context ContainerRequestContext containerRequestContext) {
        .... processing ....
}

因为,数据类型不匹配API获得响应错误如下:

Status Code : 400
Status Message : Bad Request
Body:
    Can not construct instance of java.lang.Integer from String value 'myvalue': 
    not a valid Integer value at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@bd8b3db; line: 5, column: 15] 

由于数据类型不匹配,Jersey抛出无效的数据类型错误。

不幸的是,我无法捕获此异常,因为由于数据类型解析中的异常,请求不会进入控制器方法。

想知道,我怎样才能捕获此异常,以便我可以将错误响应更改为有意义的内容。

谢谢。

jax-rs jersey-2.0 jsonparser
1个回答
1
投票

您可以通过实现错误映射器来处理此问题。对于上面显示的示例,在将JSON数据映射到POJO时,看起来异常会被内部处理抛出。

如果仔细查看日志,在处理数据时会发现InvalidFormatExceptionJsonMappingException等错误。

您可以为正在获得的错误创建Exception Mapper。我建议使用超级JsonMappingException,因为它会处理错误,如无效类型,请求有效负载中的无效JSON等:

@Provider
public class GenericExceptionMapper extends Throwable implements ExceptionMapper<JsonMappingException> {
    @Override
    public Response toResponse(JsonMappingException thrExe) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("errorMessage", "Invalid input provided");
        return Response.status(400).entity(jsonObject.toString())
        .type("application/json").build();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.