Look at ResponseStatusException's cause for binding errors

Fixes gh-41984
This commit is contained in:
Andy Wilkinson 2024-08-21 17:02:30 +01:00
parent b2887303a6
commit 0610fda733
2 changed files with 18 additions and 0 deletions

View File

@ -122,6 +122,9 @@ public class DefaultErrorAttributes implements ErrorAttributes {
else if (error instanceof ResponseStatusException responseStatusException) {
errorAttributes.put("message", responseStatusException.getReason());
exception = (responseStatusException.getCause() != null) ? responseStatusException.getCause() : error;
if (exception instanceof BindingResult bindingResult) {
errorAttributes.put("errors", bindingResult.getAllErrors());
}
}
else {
exception = error;

View File

@ -250,6 +250,21 @@ class DefaultErrorAttributesTests {
assertThat(attributes).containsEntry("errors", bindingResult.getAllErrors());
}
@Test
void extractBindingResultErrorsThatCausedAResponseStatusException() throws Exception {
Method method = getClass().getDeclaredMethod("method", String.class);
MethodParameter stringParam = new MethodParameter(method, 0);
BindingResult bindingResult = new MapBindingResult(Collections.singletonMap("a", "b"), "objectName");
bindingResult.addError(new ObjectError("c", "d"));
Exception ex = new WebExchangeBindException(stringParam, bindingResult);
MockServerHttpRequest request = MockServerHttpRequest.get("/test").build();
Map<String, Object> attributes = this.errorAttributes.getErrorAttributes(
buildServerRequest(request, new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid", ex)),
ErrorAttributeOptions.of(Include.MESSAGE, Include.BINDING_ERRORS));
assertThat(attributes.get("message")).isEqualTo("Invalid");
assertThat(attributes).containsEntry("errors", bindingResult.getAllErrors());
}
@Test
void extractMethodValidationResultErrors() throws Exception {
Object target = "test";