Spring Boot @ExceptionHandler hide Exception Name
You can get the Error Attributes in your controller advice and then, only keep the Exposable Fields. Something like following:
@ControllerAdvice
public class ExcptionController {
private static final List<String> EXPOSABLE_FIELDS = asList("timestamp", "status", "error", "message", "path");
@Autowired private ErrorAttributes errorAttributes;
@ExceptionHandler(UnsatisfiedServletRequestParameterException.class)
private ResponseEntity foo(HttpServletRequest request) {
Map<String, Object> errors = getErrorAttributes(request);
errors.put("message", "Invalid parameter");
return ResponseEntity.badRequest().body(errors);
}
private Map<String, Object> getErrorAttributes(HttpServletRequest request) {
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
final boolean WITHOUT_STACK_TRACE = false;
Map<String, Object> attributes = errorAttributes.getErrorAttributes(requestAttributes, WITHOUT_STACK_TRACE);
// log exception before removing it
attributes.keySet().removeIf(key -> !EXPOSABLE_FIELDS.contains(key));
return attributes;
}
}
For those who use spring boot 2.x.
Since version 2.0.0 default implemetation of ErrorAttrubutes is DefaultErrorAttributes.
When possible DefaultErrorAttributes provides exception stack trace. Deleting this field from the answer is possible by setting:
server.error.include-stacktrace: never
I have solved this bean-style. Adding the following bean definition to REST layer configuration replacing ErrorAttributes
used solved issue in my case without any runtime code on exception processing.
@Bean
public ErrorAttributes errorAttributes() {
return new DefaultErrorAttributes() {
@Override
public Map<String, Object> getErrorAttributes(
RequestAttributes requestAttributes,
boolean includeStackTrace) {
Map<String, Object> errorAttributes
= super.getErrorAttributes(requestAttributes, includeStackTrace);
errorAttributes.remove("exception");
return errorAttributes;
}
};
}