Skip to content

Commit 614c7b0

Browse files
committed
ResponseStatusException associated headers
A ResponseStatus exception now exposes extra method to return headers for the response. This is used in ResponseStatusExceptionHandler to apply the headers to the response. Closes gh-23741
1 parent cc84533 commit 614c7b0

File tree

5 files changed

+95
-16
lines changed

5 files changed

+95
-16
lines changed

spring-web/src/main/java/org/springframework/web/server/MethodNotAllowedException.java

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -19,12 +19,15 @@
1919
import java.util.Collection;
2020
import java.util.Collections;
2121
import java.util.HashSet;
22+
import java.util.Map;
2223
import java.util.Set;
2324

2425
import org.springframework.http.HttpMethod;
2526
import org.springframework.http.HttpStatus;
2627
import org.springframework.lang.Nullable;
2728
import org.springframework.util.Assert;
29+
import org.springframework.util.CollectionUtils;
30+
import org.springframework.util.StringUtils;
2831

2932
/**
3033
* Exception for errors that fit response status 405 (method not allowed).
@@ -37,7 +40,7 @@ public class MethodNotAllowedException extends ResponseStatusException {
3740

3841
private final String method;
3942

40-
private final Set<HttpMethod> supportedMethods;
43+
private final Set<HttpMethod> httpMethods;
4144

4245

4346
public MethodNotAllowedException(HttpMethod method, Collection<HttpMethod> supportedMethods) {
@@ -51,10 +54,21 @@ public MethodNotAllowedException(String method, @Nullable Collection<HttpMethod>
5154
supportedMethods = Collections.emptySet();
5255
}
5356
this.method = method;
54-
this.supportedMethods = Collections.unmodifiableSet(new HashSet<>(supportedMethods));
57+
this.httpMethods = Collections.unmodifiableSet(new HashSet<>(supportedMethods));
5558
}
5659

5760

61+
/**
62+
* Return a Map with an "Allow" header.
63+
* @since 5.1.11
64+
*/
65+
@Override
66+
public Map<String, String> getHeaders() {
67+
return !CollectionUtils.isEmpty(this.httpMethods) ?
68+
Collections.singletonMap("Allow", StringUtils.collectionToDelimitedString(this.httpMethods, ", ")) :
69+
Collections.emptyMap();
70+
}
71+
5872
/**
5973
* Return the HTTP method for the failed request.
6074
*/
@@ -66,6 +80,7 @@ public String getHttpMethod() {
6680
* Return the list of supported HTTP methods.
6781
*/
6882
public Set<HttpMethod> getSupportedMethods() {
69-
return this.supportedMethods;
83+
return this.httpMethods;
7084
}
85+
7186
}

spring-web/src/main/java/org/springframework/web/server/NotAcceptableStatusException.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,11 @@
1818

1919
import java.util.Collections;
2020
import java.util.List;
21+
import java.util.Map;
2122

2223
import org.springframework.http.HttpStatus;
2324
import org.springframework.http.MediaType;
25+
import org.springframework.util.CollectionUtils;
2426

2527
/**
2628
* Exception for errors that fit response status 406 (not acceptable).
@@ -51,6 +53,17 @@ public NotAcceptableStatusException(List<MediaType> supportedMediaTypes) {
5153
}
5254

5355

56+
/**
57+
* Return a Map with an "Accept" header, or an empty map.
58+
* @since 5.1.11
59+
*/
60+
@Override
61+
public Map<String, String> getHeaders() {
62+
return !CollectionUtils.isEmpty(this.supportedMediaTypes) ?
63+
Collections.singletonMap("Accept", MediaType.toString(this.supportedMediaTypes)) :
64+
Collections.emptyMap();
65+
}
66+
5467
/**
5568
* Return the list of supported content types in cases when the Accept
5669
* header is parsed but not supported, or an empty list otherwise.

spring-web/src/main/java/org/springframework/web/server/ResponseStatusException.java

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -16,6 +16,9 @@
1616

1717
package org.springframework.web.server;
1818

19+
import java.util.Collections;
20+
import java.util.Map;
21+
1922
import org.springframework.core.NestedExceptionUtils;
2023
import org.springframework.core.NestedRuntimeException;
2124
import org.springframework.http.HttpStatus;
@@ -72,12 +75,21 @@ public ResponseStatusException(HttpStatus status, @Nullable String reason, @Null
7275

7376

7477
/**
75-
* The HTTP status that fits the exception (never {@code null}).
78+
* Return the HTTP status associated with this exception.
7679
*/
7780
public HttpStatus getStatus() {
7881
return this.status;
7982
}
8083

84+
/**
85+
* Return response headers associated with the exception, possibly required
86+
* for the given status code (e.g. "Allow", "Accept").
87+
* @since 5.1.11
88+
*/
89+
public Map<String, String> getHeaders() {
90+
return Collections.emptyMap();
91+
}
92+
8193
/**
8294
* The reason explaining the exception (potentially {@code null} or empty).
8395
*/
@@ -86,6 +98,7 @@ public String getReason() {
8698
return this.reason;
8799
}
88100

101+
89102
@Override
90103
public String getMessage() {
91104
String msg = this.status + (this.reason != null ? " \"" + this.reason + "\"" : "");

spring-web/src/main/java/org/springframework/web/server/handler/ResponseStatusExceptionHandler.java

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -22,6 +22,7 @@
2222

2323
import org.springframework.http.HttpStatus;
2424
import org.springframework.http.server.reactive.ServerHttpRequest;
25+
import org.springframework.http.server.reactive.ServerHttpResponse;
2526
import org.springframework.lang.Nullable;
2627
import org.springframework.web.server.ResponseStatusException;
2728
import org.springframework.web.server.ServerWebExchange;
@@ -62,8 +63,7 @@ public void setWarnLogCategory(String loggerName) {
6263

6364
@Override
6465
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
65-
HttpStatus status = resolveStatus(ex);
66-
if (status == null || !exchange.getResponse().setStatusCode(status)) {
66+
if (!updateResponse(exchange.getResponse(), ex)) {
6767
return Mono.error(ex);
6868
}
6969

@@ -86,16 +86,25 @@ private String formatError(Throwable ex, ServerHttpRequest request) {
8686
return "Resolved [" + reason + "] for HTTP " + request.getMethod() + " " + path;
8787
}
8888

89-
@Nullable
90-
private HttpStatus resolveStatus(Throwable ex) {
89+
private boolean updateResponse(ServerHttpResponse response, Throwable ex) {
90+
boolean result = false;
9191
HttpStatus status = determineStatus(ex);
92-
if (status == null) {
92+
if (status != null) {
93+
if (response.setStatusCode(status)) {
94+
if (ex instanceof ResponseStatusException) {
95+
((ResponseStatusException) ex).getHeaders()
96+
.forEach((name, value) -> response.getHeaders().add(name, value));
97+
}
98+
result = true;
99+
}
100+
}
101+
else {
93102
Throwable cause = ex.getCause();
94103
if (cause != null) {
95-
status = resolveStatus(cause);
104+
result = updateResponse(response, cause);
96105
}
97106
}
98-
return status;
107+
return result;
99108
}
100109

101110
/**

spring-web/src/test/java/org/springframework/web/server/handler/ResponseStatusExceptionHandlerTests.java

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -17,18 +17,27 @@
1717
package org.springframework.web.server.handler;
1818

1919
import java.time.Duration;
20+
import java.util.Arrays;
2021

2122
import org.junit.Before;
2223
import org.junit.Test;
2324
import reactor.core.publisher.Mono;
2425
import reactor.test.StepVerifier;
2526

27+
import org.springframework.http.HttpMethod;
2628
import org.springframework.http.HttpStatus;
29+
import org.springframework.http.MediaType;
2730
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
31+
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
2832
import org.springframework.mock.web.test.server.MockServerWebExchange;
33+
import org.springframework.web.server.MethodNotAllowedException;
34+
import org.springframework.web.server.NotAcceptableStatusException;
2935
import org.springframework.web.server.ResponseStatusException;
3036

31-
import static org.junit.Assert.*;
37+
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
38+
import static org.junit.Assert.assertEquals;
39+
import static org.junit.Assert.assertSame;
40+
import static org.junit.Assert.assertThat;
3241

3342
/**
3443
* Unit tests for {@link ResponseStatusExceptionHandler}.
@@ -67,6 +76,26 @@ public void handleNestedResponseStatusException() {
6776
assertEquals(HttpStatus.BAD_REQUEST, this.exchange.getResponse().getStatusCode());
6877
}
6978

79+
@Test // gh-23741
80+
public void handleMethodNotAllowed() {
81+
Throwable ex = new MethodNotAllowedException(HttpMethod.PATCH, Arrays.asList(HttpMethod.POST, HttpMethod.PUT));
82+
this.handler.handle(this.exchange, ex).block(Duration.ofSeconds(5));
83+
84+
MockServerHttpResponse response = this.exchange.getResponse();
85+
assertEquals(HttpStatus.METHOD_NOT_ALLOWED, response.getStatusCode());
86+
assertThat(response.getHeaders().getAllow(), contains(HttpMethod.POST, HttpMethod.PUT));
87+
}
88+
89+
@Test // gh-23741
90+
public void handleResponseStatusExceptionWithHeaders() {
91+
Throwable ex = new NotAcceptableStatusException(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.TEXT_HTML));
92+
this.handler.handle(this.exchange, ex).block(Duration.ofSeconds(5));
93+
94+
MockServerHttpResponse response = this.exchange.getResponse();
95+
assertEquals(HttpStatus.NOT_ACCEPTABLE, response.getStatusCode());
96+
assertThat(response.getHeaders().getAccept(), contains(MediaType.TEXT_PLAIN, MediaType.TEXT_HTML));
97+
}
98+
7099
@Test
71100
public void unresolvedException() {
72101
Throwable expected = new IllegalStateException();

0 commit comments

Comments
 (0)