Throw 404 ResponseStatusException when no routes found

This commit makes it possible to customize 404 responses generated by
RouterFunctionWebHandler, by throwing an ResponseStatusException
instead of returning a standard 404 response.

See gh-25358
This commit is contained in:
Ingmar van Dijk
2020-07-06 09:13:07 +02:00
committed by Arjen Poutsma
parent 5649a6f8ef
commit 69df27a99f
2 changed files with 27 additions and 9 deletions

View File

@@ -16,14 +16,17 @@
package org.springframework.web.reactive.function.server;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
@@ -191,6 +194,27 @@ public class RouterFunctionsTests {
assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}
@Test
public void toHttpHandlerRouteNotFoundReturnsResponseStatusException() {
HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.accepted().build();
RouterFunction<ServerResponse> routerFunction =
RouterFunctions.route(RequestPredicates.GET("/path"), handlerFunction);
HandlerStrategies handlerStrategies = HandlerStrategies.empty().exceptionHandler((exchange, ex) -> {
exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
DataBuffer buffer = exchange.getResponse().bufferFactory().wrap("Custom response".getBytes(StandardCharsets.UTF_8));
return exchange.getResponse().writeWith(Flux.just(buffer));
}).build();
HttpHandler result = RouterFunctions.toHttpHandler(routerFunction, handlerStrategies);
assertThat(result).isNotNull();
MockServerHttpRequest httpRequest = MockServerHttpRequest.get("https://localhost").build();
MockServerHttpResponse httpResponse = new MockServerHttpResponse();
result.handle(httpRequest, httpResponse).block();
assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(httpResponse.getBodyAsString().block()).isEqualTo("Custom response");
}
@Test
public void toHttpHandlerHandlerReturnResponseStatusExceptionInResponseWriteTo() {
HandlerFunction<ServerResponse> handlerFunction =