Skip to content

Commit

Permalink
Log warning if ResponseStatus 'reason' is set and handler returns value
Browse files Browse the repository at this point in the history
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
  • Loading branch information
quaff authored and bclozel committed Sep 7, 2023
1 parent bc69542 commit 94a49c4
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@
/**
* 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 "";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,9 @@ private void evaluateResponseStatus() {

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.");
}
}
}

Expand Down

0 comments on commit 94a49c4

Please sign in to comment.