Ensure handling of 404 errors for static resources

Closes gh-30930
This commit is contained in:
rstoyanchev
2023-07-27 22:09:18 +03:00
parent 85704c890e
commit 78d0dbb519
6 changed files with 194 additions and 10 deletions

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.resource;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
/**
* Raised when {@link ResourceWebHandler} is mapped to the request but can not
* find a matching resource.
*
* @author Rossen Stoyanchev
* @since 6.1
*/
@SuppressWarnings("serial")
public class NoResourceFoundException extends ResponseStatusException {
public NoResourceFoundException(String resourcePath) {
super(HttpStatus.NOT_FOUND, "No static resource " + resourcePath + ".");
setDetail(getReason());
}
}

View File

@@ -41,7 +41,6 @@ import org.springframework.core.log.LogFormatUtils;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.http.codec.ResourceHttpMessageWriter;
@@ -54,7 +53,6 @@ import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.server.MethodNotAllowedException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebHandler;
import org.springframework.web.util.pattern.PathPattern;
@@ -403,7 +401,7 @@ public class ResourceWebHandler implements WebHandler, InitializingBean {
return getResource(exchange)
.switchIfEmpty(Mono.defer(() -> {
logger.debug(exchange.getLogPrefix() + "Resource not found");
return Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND));
return Mono.error(new NoResourceFoundException(getResourcePath(exchange)));
}))
.flatMap(resource -> {
try {