Log warning if ResponseStatus 'reason' is set and handler returns value

When a handler method is annotated with `@ResponseStatus(reason="...")`,
Spring MVC will use `HttpServletResponse#sendError` to complete the
response. As a result, the Servlet container will send an HTML error
page and any existing data in the response buffer will be cleared.

This commit clarifies the `@ResponseStatus` Javadoc and ensures that a
message is logged at the WARN level if a handler method is annotated
like this and still returns a non-Void value. In this case, the return
value will be ignored and developers should be aware of this fact.

See gh-31113
Closes gh-31121
This commit is contained in:
Yanming Zhou 2023-08-28 10:31:36 +08:00 committed by Brian Clozel
parent bc6954255b
commit 94a49c4ed3
2 changed files with 5 additions and 1 deletions

View File

@ -80,7 +80,8 @@ public @interface ResponseStatus {
/**
* The <em>reason</em> to be used for the response.
* <p>Defaults to an empty string which will be ignored. Set the reason to a
* non-empty value to have it used for the response.
* non-empty value to have it used to send a Servlet container error page.
* In this case, the return value of the handler method will be ignored.
* @see jakarta.servlet.http.HttpServletResponse#sendError(int, String)
*/
String reason() default "";

View File

@ -216,6 +216,9 @@ public class HandlerMethod extends AnnotatedMethod {
this.responseStatus = annotation.code();
this.responseStatusReason = resolvedReason;
if (StringUtils.hasText(this.responseStatusReason) && getMethod().getReturnType() != void.class) {
logger.warn("Return value of [" + getMethod() + "] will be ignored since @ResponseStatus 'reason' attribute is set.");
}
}
}