Friday, March 29, 2013

Spring RequestBody Mapping Errors

If you have error gotten back a nice 400 Bad Request from Spring MVC when trying to map a pojo with @RequestBody this will help you find out what is failing.


@ExceptionHandler(MethodArgumentNotValidException.class)
public String handleMethodArgumentNotValidException(
MethodArgumentNotValidException error) {
LOGGER.error(error.getBindingResult().toString());
return "Bad value";
}

@ExceptionHandler(TypeMismatchException.class)
public String handleTypeMismatchException(TypeMismatchException ex,
HttpServletRequest req, HttpServletResponse resp) {
LOGGER.error("Parameter failure: {}"
+ ex.getRootCause().getLocalizedMessage());
LOGGER.error("Invalid value is: {}" + ex.getValue());
LOGGER.error("Required type is: {}"
+ ex.getRequiredType().getSimpleName());

return "Bad value";
}

@ExceptionHandler(HttpMessageNotReadableException.class)
public String handleMessageNotReadableException(
HttpMessageNotReadableException ex, HttpServletRequest req,
HttpServletResponse resp) {
LOGGER.error("Failure: {}" + ex.getRootCause().getLocalizedMessage());

return "Bad value";
}

1 comment: