泽西岛:给定无效的请求正文时,返回400错误而不是500错误 [英] Jersey: Returning 400 error instead of 500 when given invalid request body

查看:107
本文介绍了泽西岛:给定无效的请求正文时,返回400错误而不是500错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jersey的集成Jackson处理将传入的JSON转换为POJO,例如:

I'm using Jersey's integrated Jackson processing to transform incoming JSON to a POJO, e.g.:

@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response newCustomer( CustomerRepresentation customer)
{
...
}

如果客户端发送带有无效字段的JSON,Jersey当前返回500 Internal Server Error.相反,我想返回一个400 Bad Request,最好返回一些有意义的细节,以指示哪些字段有误.

If a client sends JSON with invalid fields Jersey currently returns a 500 Internal Server Error. Instead, I'd like to return a 400 Bad Request, preferably with some meaningful detail indicating which fields are in error.

对如何实现此目标有任何见解? (至少返回通用400而不是完全不合适的500?)

Any insight into how this could be accomplished? (At least returning a generic 400 instead of the completely inappropriate 500?)

更新: 这是在调用处理程序之前在服务器端生成的异常:

Update: Here's the exception being generated server-side, before my handler is invoked:

javax.servlet.ServletException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: 
Unrecognized field "this_isnt_a_known"_field" (Class com.redacted....), not marked as ignorable

推荐答案

我终于能够通过实现ExceptionMapper来捕获Jackson抛出的UnrecognizedPropertyException并将其映射到400 Bad Request响应来解决此问题. :

I was finally able to work around this problem by implementing an ExceptionMapper to catch the UnrecognizedPropertyException thrown by Jackson and map it to a 400 Bad Request response:

@Provider
public class UnrecognizedPropertyExceptionMapper implements ExceptionMapper<UnrecognizedPropertyException>
{

    @Override
    public Response toResponse(UnrecognizedPropertyException exception)
    {
        return Response
                .status(Response.Status.BAD_REQUEST)
                .entity( "'" + exception.getUnrecognizedPropertyName() + "' is an unrecognized field.")
                .type( MediaType.TEXT_PLAIN)
                .build();
    }

}

这篇关于泽西岛:给定无效的请求正文时,返回400错误而不是500错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆