Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to see JSON conversion error in Spring MVC REST

I am doing AngularJS and Spring REST application. Here is my code.

  @RestController
  @RequestMapping("/user")
  // @Secured("ROLE_ADMIN")
  public class UserController
  {
    @RequestMapping(value = "/verifyUser", method = RequestMethod.POST)
    public Boolean verifyUser(@RequestBody User user)
    {
    }
  } 

If user object is not in correct format then browser says 400 (Bad Request) No other error is displayed in Eclipse console. I just want to see what exact error occured in deserialization if user object is in incorrect format.

like image 545
Rajendra Thorat Avatar asked Oct 21 '14 12:10

Rajendra Thorat


2 Answers

If you don't want to use the custom objectMapper or you don't want to use String as method input, you can use spring ExceptionHandler. Simply add the following method into your controller and then you can see the jackson databind errors in your console.

@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="There was an error processing the request body.")
public void handleMessageNotReadableException(HttpServletRequest request, HttpMessageNotReadableException exception) {
    System.out.println("\nUnable to bind post data sent to: " + request.getRequestURI() + "\nCaught Exception:\n" + exception.getMessage());
}

spring documentation: Expception handling in Spring MVC

If you want to ignore some useless jackson exceptions, you can use your own jackson ObjectMapper in the springframework. just see this answer.

like image 119
Dariush Jafari Avatar answered Nov 19 '22 11:11

Dariush Jafari


Convert your method like below. Use ObjectMapper to convert the JSON to the object,so while converting it will throw exception and you will be able to identify the problem.

@RequestMapping(value = "/verifyUser", method = RequestMethod.POST)
    public Boolean verifyUser(@RequestBody String json)
    {  
       try{
           ObjectMapper om = new ObjectMapper();
           User user = om.readValue(json, User.class);
          } 
          catch(Exception e){
            e.printStackTrace()
          }
         // Write your logic.....
        return ....;       

    }
like image 21
dReAmEr Avatar answered Nov 19 '22 11:11

dReAmEr