Jersey: Returning 400 error instead of 500 when given invalid request body

前端 未结 4 1955
予麋鹿
予麋鹿 2021-02-18 15:24

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

@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response newCus         


        
4条回答
  •  鱼传尺愫
    2021-02-18 16:21

    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
    {
    
        @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();
        }
    
    }
    

提交回复
热议问题