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

@@ -59,7 +59,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class ResponseEntityExceptionHandlerTests {
private final ResponseEntityExceptionHandler exceptionHandler = new GlobalExceptionHandler();
private final GlobalExceptionHandler exceptionHandler = new GlobalExceptionHandler();
private final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
@@ -149,6 +149,29 @@ public class ResponseEntityExceptionHandlerTests {
"Content-Type application/json not supported. Supported: [application/atom+xml, application/xml]");
}
@Test
void customExceptionToProblemDetailViaMessageSource() {
Locale locale = Locale.UK;
LocaleContextHolder.setLocale(locale);
StaticMessageSource messageSource = new StaticMessageSource();
messageSource.addMessage(
"problemDetail." + IllegalStateException.class.getName(), locale,
"Invalid state: {0}");
this.exceptionHandler.setMessageSource(messageSource);
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")
.acceptLanguageAsLocales(locale).build());
ResponseEntity<?> responseEntity =
this.exceptionHandler.handleException(new IllegalStateException(), exchange).block();
ProblemDetail body = (ProblemDetail) responseEntity.getBody();
assertThat(body.getDetail()).isEqualTo("Invalid state: A");
}
@SuppressWarnings("unchecked")
private ResponseEntity<ProblemDetail> testException(ErrorResponseException exception) {
@@ -247,6 +270,12 @@ public class ResponseEntityExceptionHandlerTests {
return handleAndSetTypeToExceptionName(ex, headers, status, exchange);
}
public Mono<ResponseEntity<Object>> handleException(IllegalStateException ex, ServerWebExchange exchange) {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
ProblemDetail body = createProblemDetail(ex, status, null, ex.getMessage(), null, new Object[] {"A"}, exchange);
return handleExceptionInternal(ex, body, null, status, exchange);
}
}
}