Using Spring MVC, accepting POST requests with bad JSON leads to a default 400 error code server page being returned

后端 未结 1 1277
傲寒
傲寒 2021-02-13 13:59

I am working on a REST api. Receiving a POST message with bad JSON (e.g. { sdfasdfasdf } ) causes Spring to return the default server page for a 400 Bad Request Error. I do no

1条回答
  •  抹茶落季
    2021-02-13 14:26

    This was raised as an issue with Spring SPR-7439 - JSON (jackson) @RequestBody marshalling throws awkward exception - which was fixed in Spring 3.1M2 by having Spring throw a org.springframework.http.converter.HttpMessageNotReadableException in the case of a missing or invalid message body.

    In your code you cannot create a ResponseStatus since it is abstract but I tested catching this exception with a simpler method locally with Spring 3.2.0.RELEASE running on Jetty 9.0.3.v20130506.

    @ExceptionHandler({org.springframework.http.converter.HttpMessageNotReadableException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public String resolveException() {
        return "error";
    }
    

    and I received a 400 status "error" String response.

    The defect was discussed on this Spring forum post.

    Note: I started testing with Jetty 9.0.0.M4 but that had some other internal issues stopping the @ExceptionHandler completing, so depending on your container (Jetty, Tomcat, other) version you might need to get a newer version that plays nicely with whatever version of Spring you are using.

    0 讨论(0)
提交回复
热议问题