Skip to content

Instantly share code, notes, and snippets.

@jkuipers
Created April 8, 2018 13:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkuipers/8da7820c2aca4f40b2c1cb846e04cc9d to your computer and use it in GitHub Desktop.
Save jkuipers/8da7820c2aca4f40b2c1cb846e04cc9d to your computer and use it in GitHub Desktop.
Example of custom Spring Boot ErrorAttributes which resolves ObjectErrors (incl. FieldErrors) rather than serializing them fully
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.context.MessageSource;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.context.request.WebRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Overrides {@link DefaultErrorAttributes#getErrorAttributes(WebRequest, boolean)} by mapping its list of
* {@code ObjectErrors} to just a list of error messages, to avoid exposing too much detail about binding and
* validation errors to clients.
*/
public class ResolvedErrorAttributes extends DefaultErrorAttributes {
private MessageSource messageSource;
public ResolvedErrorAttributes(MessageSource messageSource) {
this.messageSource = messageSource;
}
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);
resolveBindingErrors(errorAttributes);
return errorAttributes;
}
private void resolveBindingErrors(Map<String, Object> errorAttributes) {
List<ObjectError> errors = (List<ObjectError>) errorAttributes.get("errors");
if (errors == null) {
return;
}
List<String> errorMessages = new ArrayList<>();
for (ObjectError error : errors) {
String resolved = messageSource.getMessage(error, Locale.US);
if (error instanceof FieldError) {
FieldError fieldError = (FieldError) error;
errorMessages.add(fieldError.getField() + " " + resolved + " but value was " + fieldError.getRejectedValue());
} else {
errorMessages.add(resolved);
}
}
errorAttributes.put("errors", errorMessages);
}
}
@abhi4151
Copy link

abhi4151 commented Aug 27, 2018

Can you please show an example of how to use this implementation? I tried using this implementation but is not working somehow:

spring-projects/spring-boot#14211

@jkuipers
Copy link
Author

@abhi4151 simply registering it as an “errorAttributes” bean should do the trick.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment