Created
December 12, 2020 18:22
-
-
Save susimsek/2f7ff555a20e24990d2bf35d9b7ca0d7 to your computer and use it in GitHub Desktop.
Spring REST Custom Error Handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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