Improve mapping any Exception to ErrorResponse

Add protected, convenience method in ResponseEntityExceptionHandler
to create a ProblemDetail for any exception, along with a
MessageSource lookup for the "detail" field.

Closes gh-29384
This commit is contained in:
rstoyanchev
2022-11-01 11:40:23 +00:00
parent 210019cad1
commit 506fbe5243
5 changed files with 171 additions and 52 deletions

View File

@@ -16,6 +16,7 @@
package org.springframework.web.servlet.mvc.method.annotation;
import java.beans.PropertyChangeEvent;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -192,6 +193,30 @@ public class ResponseEntityExceptionHandlerTests {
testException(new TypeMismatchException("foo", String.class));
}
@Test
public void typeMismatchWithProblemDetailViaMessageSource() {
Locale locale = Locale.UK;
LocaleContextHolder.setLocale(locale);
try {
StaticMessageSource messageSource = new StaticMessageSource();
messageSource.addMessage(
"problemDetail." + TypeMismatchException.class.getName(), locale,
"Failed to set {0} to value: {1}");
this.exceptionHandler.setMessageSource(messageSource);
ResponseEntity<?> entity = testException(
new TypeMismatchException(new PropertyChangeEvent(this, "name", "John", "James"), String.class));
ProblemDetail body = (ProblemDetail) entity.getBody();
assertThat(body.getDetail()).isEqualTo("Failed to set name to value: James");
}
finally {
LocaleContextHolder.resetLocaleContext();
}
}
@Test
@SuppressWarnings("deprecation")
public void httpMessageNotReadable() {