应用程序我正在为 spring 云网关内的前端应用程序的静态文件提供服务。目前,除预定义一次之外的任何路由都按预期最终为 404。
@Bean
public RouterFunction<ServerResponse> htmlRemoteAppointmentRouter(
@Value("classpath:/static/index.html")
Resource html) {
return route(GET("/"), request -> ok().contentType(MediaType.TEXT_HTML).bodyValue(html))
.andRoute(GET("/home/{*path}"), request -> ok().contentType(MediaType.TEXT_HTML).bodyValue(html))
.andRoute(GET("/user/{*path}"), request -> ok().contentType(MediaType.TEXT_HTML).bodyValue(html));
}
然而,我期望的是处理 404 错误并为所有失败的 GET 请求提供 index.html。
我尝试添加 /error
映射。但是在客户端,它仍然显示 404 的 Whitelabel Error Page
。
@Controller
public class ErrorHandler implements ErrorController {
@RequestMapping("/error")
public String something() {
return "error";
}
}
最佳答案
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class ErrorHandler implements ErrorController {
@ResponseBody
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public String errorHtml() {
return "custom error controller";
}
}
请求映射基本上是从BasicErrorController的源代码中复制过来的。 参见 https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java
@ResponseBody
注释是必需的,因为该方法正在返回一个字符串。另外两个@RequestMapping
注解是直接从源码复制过来的。
关于java - 使用Spring Cloud Gateway时如何处理404错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73421082/