Skip to content

Instantly share code, notes, and snippets.

@susimsek
Created December 12, 2020 18:22
Show Gist options
  • Save susimsek/2f7ff555a20e24990d2bf35d9b7ca0d7 to your computer and use it in GitHub Desktop.
Save susimsek/2f7ff555a20e24990d2bf35d9b7ca0d7 to your computer and use it in GitHub Desktop.
Spring REST Custom Error Handling
@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
Map<String, Object> errorAttributes = new LinkedHashMap();
Map<String, Object> attributes = super.getErrorAttributes(webRequest, options);
long timestamp = ((Date) attributes.get("timestamp")).getTime();
errorAttributes.put("status", attributes.get("status"));
errorAttributes.put("message", attributes.get("message"));
errorAttributes.put("path", attributes.get("path"));
errorAttributes.put("timestamp", timestamp);
if(attributes.containsKey("errors")){
List<FieldError> fieldErrors = (List<FieldError>) attributes.get("errors");
Map<String, String> errors = new HashMap<>();
for(FieldError fieldError: fieldErrors){
errors.put(fieldError.getField(),fieldError.getDefaultMessage());
}
errorAttributes.put("errors",errors);
}
return errorAttributes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment