'How to return response code 400 instead of stack trace or ignoring json attribute?
When I send unsupported JSON request I receive stack trace from Jackson that it doesn't have this property. On the @JsonIgnoreProperties(ignoreUnknown = true) I just got a response without necessary obtaining as expected. But how can I return for example 400 or another response code without stack trace?
org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "dave" (Class com.atlassian.troubleshooting.jfr.domain.JfrSettings), not marked as ignorable
at [Source: org.apache.catalina.connector.CoyoteInputStream@8aaf377; line: 1, column: 14] (through reference chain: com.atlassian.troubleshooting.jfr.domain.JfrSettings["dave"])
at org.codehaus.jackson.map.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:53)
at org.codehaus.jackson.map.deser.StdDeserializationContext.unknownFieldException(StdDeserializationContext.java:267)
Solution 1:[1]
For me HttpMessageNotReadableException is thrown and UnrecognizedPropertyException is the nested exception. you can use SimpleMappingExceptionResolver and configure it like:
@Configuration
public class CustomConfiguration implements WebMvcConfigurer {
@Bean
public SimpleMappingExceptionResolver simpleMappingExceptionResolver(){
var mappings = new Properties();
mappings.setProperty("HttpMessageNotReadableException", "errorpage");
var statusCode = new Properties();
statusCode.setProperty("errorpage", String.valueOf(HttpServletResponse.SC_BAD_REQUEST));
var exeptionResolver = new SimpleMappingExceptionResolver();
exeptionResolver.setStatusCodes(statusCode);
exeptionResolver.setExceptionMappings(mappings);
return exeptionResolver;
}
@Override
public void configureHandlerExceptionResolvers(
List<HandlerExceptionResolver> resolvers) {
resolvers.add(simpleMappingExceptionResolver());
}
}
or use @ControllerAdvice like:
@ControllerAdvice
public class ControllerAdvisor {
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<Object> handleCityNotFoundException(
HttpMessageNotReadableException ex, WebRequest request) {
// do stuff with ex and request
return new ResponseEntity<>("body", HttpStatus.BAD_REQUEST);
}
}
also as I said in the beginning the exception is HttpMessageNotReadableException and UnrecognizedPropertyException is just nested inside HttpMessageNotReadableException. If you use UnrecognizedPropertyException in above codes it won't work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hatef alipoor |
