Make DefaultErrorAttributes easier to subclass for message customization

Closes gh-22378
This commit is contained in:
Andy Wilkinson
2020-07-21 10:30:33 +01:00
parent e4b065bdd9
commit 0fd567664a
2 changed files with 36 additions and 5 deletions

View File

@@ -180,14 +180,32 @@ public class DefaultErrorAttributes implements ErrorAttributes, HandlerException
}
private void addExceptionErrorMessage(Map<String, Object> errorAttributes, WebRequest webRequest, Throwable error) {
errorAttributes.put("message", getMessage(webRequest, error));
}
/**
* Returns the message to be included as the value of the {@code message} error
* attribute. By default the returned message is the first of the following that is
* not empty:
* <ol>
* <li>Value of the {@link RequestDispatcher#ERROR_MESSAGE} request attribute.
* <li>Message of the given {@code error}.
* <li>{@code No message available}.
* </ol>
* @param webRequest current request
* @param error current error, if any
* @return message to include in the error attributes
* @since 2.4.0
*/
protected String getMessage(WebRequest webRequest, Throwable error) {
Object message = getAttribute(webRequest, RequestDispatcher.ERROR_MESSAGE);
if (StringUtils.isEmpty(message) && error != null) {
message = error.getMessage();
if (!StringUtils.isEmpty(message)) {
return message.toString();
}
if (StringUtils.isEmpty(message)) {
message = "No message available";
if (error != null && !StringUtils.isEmpty(error.getMessage())) {
return error.getMessage();
}
errorAttributes.put("message", message);
return "No message available";
}
private void addBindingResultErrorMessage(Map<String, Object> errorAttributes, BindingResult result) {

View File

@@ -257,4 +257,17 @@ class DefaultErrorAttributesTests {
assertThat(attributes.get("path")).isEqualTo("path");
}
@Test
void whenGetMessageIsOverridenThenMessageAttributeContainsValueReturnedFromIt() {
Map<String, Object> attributes = new DefaultErrorAttributes() {
@Override
protected String getMessage(WebRequest webRequest, Throwable error) {
return "custom message";
}
}.getErrorAttributes(this.webRequest, ErrorAttributeOptions.of(Include.MESSAGE));
assertThat(attributes).containsEntry("message", "custom message");
}
}