Failed to see JSON conversion error in Spring MVC REST

I am using 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 the user object is not in the correct format, the browser says 400 (Bad Request) No other error is displayed in the Eclipse console. I just want to find out exactly what error occurred during deserialization if the user object is in the wrong format.

+5
source share
2 answers

Convert your method as shown below. Use ObjectMapper to convert JSON to an object, so when converting it will throw an exception and you can 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 ....; } 
+4
source

If you do not want to use a custom objectMapper or do not want to use String as the input to a method, you can use spring ExceptionHandler . Just add the following method to your controller, and then you will see jackson database errors in the 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: Exception handling in spring MVC

If you want to ignore some of Jackson's useless exceptions, you can use your own Jackson ObjectMapper in springframework. just see this answer .

+5
source

Source: https://habr.com/ru/post/1205179/


All Articles