如何在Spring MVC中处理400错误

时间:2016-05-10 11:53:21

标签: java json spring rest spring-mvc

当我传递无效的json格式时,我得到400 Http响应,
我想返回自定义json消息而不是这个,任何人都可以建议如何在Spring 4.1中做什么?

使用ControllerAdvice处理Execption,但它无效。

@ControllerAdvice
public class GlobalControllerExceptionHandler  {

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

}

spring-config.xml在下面给出

<bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="1" />
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <!-- Renders JSON View -->
                <bean
                    class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
            </list>
        </property>
    </bean>

从WebSphere应用服务器(7.0)下面给出Json请求和响应。

Request 1: Empty json request : {}
Response Status Code: 400 Bad Request
Response Message    : Json request contains invalid data:null


Request 2:Invalid format of Json Request : {"data":,"name":"java"}
Response Status Code: 400 Bad Request
Response  or Exception message     :

nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected character (',' (code 44)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: com.ibm.ws.webcontainer.srt.http.HttpInputStream@8f308f3; line: 5, column: 57]

类似的问题如下链接 Using Spring MVC, accepting POST requests with bad JSON leads to a default 400 error code server page being returned

3 个答案:

答案 0 :(得分:1)

您可以尝试以这种方式映射异常。此代码将返回400状态,但您可以使用与发布的链接相同的方式更改返回

@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void handleJsonMappingException(JsonMappingException ex) {}

答案 1 :(得分:1)

最后,我通过Servlet Filter使用HttpServletRequestWrapper处理异常。

步骤1:添加过滤器
第2步:从Customize HttpServletRequestWrapper类获取请求体 第3步:使用JSON API将请求主体json字符串转换为java对象 第4步:链接请求/响应
步骤5:捕获异常/并更新HttpServlet响应

使用以下参考。

Filter Example

HttpServletRequestWrapper Example

String to Json Object

借助这种方法,我可以处理400/405/415 Http错误。

答案 2 :(得分:0)

您可以尝试在pom.xml中添加依赖项:

<!-- Need this for json to/from object -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.6.3</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.3</version>
    </dependency>

这将在您返回时自动将您的java对象转换为JSON。就像你可以写一个响应类:

public class Response {
private int responseCode;
private String responseMessage;
//as many fields as you like
public Response (int responseCode, String responseMessage) {
    this.responseCode = responseCode;
    this.responseMessage = responseMessage;
} }

然后你可以返回任何java对象,它们将作为JSON接收,

@RequestMapping(value="/someMethod", method=RequestMethod.POST)
public @ResponseBody Response someMethod(@RequestBody Parameters param) {

    return new Response(404, "your error message");
}