Skip to content

Commit

Permalink
Improve ResponseStatusException to use reason as detailMessageCode if…
Browse files Browse the repository at this point in the history
… present

detail in ProblemDetail will be localized
Closes GH-30222
  • Loading branch information
quaff committed Apr 7, 2023
1 parent d6460e0 commit 562499d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.ErrorResponseException;

/**
Expand All @@ -29,6 +30,7 @@
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @author Yanming Zhou
* @since 5.0
*/
@SuppressWarnings("serial")
Expand Down Expand Up @@ -132,4 +134,11 @@ public String getMessage() {
return getStatusCode() + (this.reason != null ? " \"" + this.reason + "\"" : "");
}

@Override
public String getDetailMessageCode() {
if (StringUtils.hasLength(this.reason)) {
return this.reason;
}
return super.getDetailMessageCode();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
Expand All @@ -72,6 +73,7 @@
* Unit tests for {@link ResponseEntityExceptionHandler}.
*
* @author Rossen Stoyanchev
* @author Yanming Zhou
*/
public class ResponseEntityExceptionHandlerTests {

Expand Down Expand Up @@ -189,6 +191,30 @@ public void errorResponseProblemDetailViaMessageSource() {
}
}

@Test
public void useResponseStatusExceptionReasonAsDetailMessageCodeIfPresent() {

Locale locale = Locale.UK;
LocaleContextHolder.setLocale(locale);

String code = "bad.request";
String message = "Breaking Bad Request";
try {
StaticMessageSource messageSource = new StaticMessageSource();
messageSource.addMessage(code, locale, message);

this.exceptionHandler.setMessageSource(messageSource);

ResponseEntity<?> entity = testException(new ResponseStatusException(HttpStatus.BAD_REQUEST, code));

ProblemDetail body = (ProblemDetail) entity.getBody();
assertThat(body.getDetail()).isEqualTo(message);
}
finally {
LocaleContextHolder.resetLocaleContext();
}
}

@Test
public void conversionNotSupported() {
testException(new ConversionNotSupportedException(new Object(), Object.class, null));
Expand Down

0 comments on commit 562499d

Please sign in to comment.