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

前端 未结 4 1957
予麋鹿
予麋鹿 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:05

    I tried mapping status 500 to status 400 with HolySamosa's answer but the exception was not caught by this mapper, and status 500 was still being returned.

    After debugging I found that JsonParseException is being thrown and not UnrecognizedPropertyException. This is because I was sending some garbage text (that was not JSON at all).

    When I sent a proper JSON from client side, with format that was not appropriate for my DTO on the server side, then I got UnrecognizedPropertyException. So there are two cases for this:

    • when you send garbage that is not JSON and
    • when you send JSON, but it is not a match for your DTO class.

    Now I am returning status 400 for both.

    0 讨论(0)
  • 2021-02-18 16:05

    I've had this same problem... Unfortunately, there's no good way that I know of to intercept the Jackson exception and generate your own error code.

    One option you have is to use @JsonIgnoreProperties and then strictly validate the deserialized object. This won't tell you if your sender transmitted junk, but if they missed required fields, you'll catch that.

    I cannot find any way to access the actual JSON passed in, other than creating an @Provider class to trap the JSON, validate it, then pass it to Jackson for deserialization.

    0 讨论(0)
  • 2021-02-18 16:16

    In dropwizard land there is an ExceptionMapper called JsonProcessingExceptionMapper that has similar functionality as to what you are looking for. Maybe you can use that for inspiration on how to address your specific issue in a non-dropwizard world.

    0 讨论(0)
  • 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<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();
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题