Vasanth
Vasanth

Reputation: 494

How to handle 400 error in Spring MVC

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 ?

Handling Execption using ControllerAdvice,but it is not working.

@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

<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).

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

Upvotes: 1

Views: 14652

Answers (3)

Vasanth
Vasanth

Reputation: 494

Finally i have handle the exception via Servlet Filter with 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

Using below reference.

Filter Example

HttpServletRequestWrapper Example

String to Json Object

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

Upvotes: 2

m26a
m26a

Reputation: 1413

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

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

Upvotes: 2

Fahad
Fahad

Reputation: 378

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

<!-- 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:

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,

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

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

Upvotes: 0

Related Questions