Spring MVC service for rest how to configure the message error message when it is Jackson deserialization error?

I have a RestController with a single method in my Spring Boot application. This method handles POST requests in the / foo url. As parameters, an identifier and a DTO object are required. Jackson deserializes the DTO object. I added the @Valid parameter to the DTO parameter to check the passed properties of the pair. My problem is that I am passing a String for the field, which should be int. This raises an HttpMessageNotReadableException, and the displayed "message" contains information about the representation of the internal object, such as class and package names. This error occurs in Jackson's deserialization logic somewhere before the hibernate check for @Valid. I can create an annotated @ExceptionHandler method in my controller that handles these types of exceptions, but then I will either have to manually output the json output, or use the default message that Spring uses from Jackson.

This is what Spring outputs when this exception occurs:

{ "timestamp": 1427473174263, "status": 400, "error": "Bad Request", "exception": "org.springframework.http.converter.HttpMessageNotReadableException", "message": "Could not read JSON: Can not construct instance of int from String value 'SHOULDNT BE A STRING': not a valid Integer value\ at [Source: java.io.PushbackInputStream@34070211 ; line: 1, column: 3] (through reference chain: com.blah.foo.dto.CustomerProductPromotionDTO[\"productId\"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of int from String value 'SHOULDNT BE A STRING': not a valid Integer value\ at [Source: java.io.PushbackInputStream@34070211 ; line: 1, column: 3] (through reference chain: com.blah.foo.dto.CustomerProductPromotionDTO[\"productId\"])", "path": "/customers/123456/promotions" } 

How to configure this message box?

+6
source share
2 answers

So, I realized that I think this is the best way to get around this Jackson error and still use Spring's default answers for relaxation. I did not know that you could use @ExceptionHandler in combination with @ResponseStatus for these non-standard exception types.

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

Spring's output above comes from the BasicErrorController , which implement the ErrorController . That way, you can implement a custom ErrorController to handle the error message format from Spring. See https://gist.github.com/jonikarppinen/662c38fb57a23de61c8b

0
source

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


All Articles