From 94a49c4ed314c024a8a983a34ab852af64f00f0b Mon Sep 17 00:00:00 2001 From: Yanming Zhou Date: Mon, 28 Aug 2023 10:31:36 +0800 Subject: [PATCH] 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 --- .../springframework/web/bind/annotation/ResponseStatus.java | 3 ++- .../java/org/springframework/web/method/HandlerMethod.java | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/ResponseStatus.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/ResponseStatus.java index 129605eec4..a6febcac12 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/ResponseStatus.java +++ b/spring-web/src/main/java/org/springframework/web/bind/annotation/ResponseStatus.java @@ -80,7 +80,8 @@ public @interface ResponseStatus { /** * The reason to be used for the response. *

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 ""; diff --git a/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java b/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java index 8ab32964e1..5474a1ce10 100644 --- a/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java +++ b/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java @@ -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."); + } } }