如何在Spring MVC中处理400错误

时间:2021-05-06 14:30:00

I am getting 400 Http response when i am passing the invalid json format,
I would like to return the custom json message instead of this , can any one advise how to do in Spring 4.1 ?

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

Handling Execption using ControllerAdvice,but it is not working.

使用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 is given below

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>

Given below Json request and response from WebSphere application server (7.0).

给出了来自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]

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

类似的问题如下链接使用Spring MVC,接受带有错误JSON的POST请求会导致返回默认的400错误代码服务器页面

3 个解决方案

#1


1  

You can attempt to map the exception this way. This code will return a 400 status, but you can change the return the same way as is the link you posted

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

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

#2


1  

Finally i have handle the exception via Servlet Filter with HttpServletRequestWrapper.

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

Step 1: Add the filter
Step 2: Get the request body from Customize HttpServletRequestWrapper class
Step 3: Convert request body json string to java object using JSON API
Step 4: Chain the request/response
Step 5: Catch exception / and update the HttpServlet Response

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

Using below reference.

使用以下参考。

Filter Example

过滤器示例

HttpServletRequestWrapper Example

HttpServletRequestWrapper示例

String to Json Object

字符串到Json对象

With the help of this approach i can handle 400/405/415 Http Errors.

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

#3


0  

You may try this, in your pom.xml add dependency:

你可以试试这个,在你的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>

this will convert your java objects to JSON automatically when you return them. like you can write a class for response:

这将在您返回时自动将您的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;
} }

then you can return any java objects and they will be received as JSON,

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

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

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

#1


1  

You can attempt to map the exception this way. This code will return a 400 status, but you can change the return the same way as is the link you posted

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

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

#2


1  

Finally i have handle the exception via Servlet Filter with HttpServletRequestWrapper.

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

Step 1: Add the filter
Step 2: Get the request body from Customize HttpServletRequestWrapper class
Step 3: Convert request body json string to java object using JSON API
Step 4: Chain the request/response
Step 5: Catch exception / and update the HttpServlet Response

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

Using below reference.

使用以下参考。

Filter Example

过滤器示例

HttpServletRequestWrapper Example

HttpServletRequestWrapper示例

String to Json Object

字符串到Json对象

With the help of this approach i can handle 400/405/415 Http Errors.

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

#3


0  

You may try this, in your pom.xml add dependency:

你可以试试这个,在你的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>

this will convert your java objects to JSON automatically when you return them. like you can write a class for response:

这将在您返回时自动将您的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;
} }

then you can return any java objects and they will be received as JSON,

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

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

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