【发布时间】:2021-12-16 18:36:02
【问题描述】:
我在获得完整的错误处理解决方案时遇到了一些麻烦。我创建了一个捕获异常和QueryTimeException 的@ControllerAdvice 类。但是,404 Not Found 消息不会转到我的自定义页面。并且 HttpStatus.GATEWAY_TIMEOUT 没有正确路由。但是,HttpStatus.REQUEST_TIMEOUT 和异常确实可以正确路由。
这是我的错误控制器。我错过了什么或做错了什么?
@ControllerAdvice
public class MyErrorController implements ErrorController {
public static final Logger logger = LoggerFactory.getLogger(MyErrorController.class);
@ExceptionHandler(HttpServerErrorException.GatewayTimeout.class)
@ResponseStatus(HttpStatus.GATEWAY_TIMEOUT)
public String gatewayTimeout() {
return "errors/error-timeout";
}
@ExceptionHandler(QueryTimeoutException.class)
@ResponseStatus(HttpStatus.REQUEST_TIMEOUT)
public String requestTimeout() {
return "errors/error-timeout";
}
@ExceptionHandler(value = {HttpClientErrorException.class, Exception.class})
public String handleExceptions() {
return "errors/error";
}
@RequestMapping("/error")
public String handleErrors(HttpServletRequest request, Exception ex) {
return "errors/error";
}
// This method is deprecated, so do not add the @Override annotation
// However, the method must remain while the Spring team has not yet removed it from the ErrorController interface
public String getErrorPath() {
return "/error";
}
}
我在 application.properties 中添加了以下内容:
server.error.whitelabel.enabled=true
server.error.path=/error
为了测试上述内容,我在控制器中添加了以下方法。
@GetMapping("/throw504")
public ResponseEntity<Void> throwGatewayTimeout() {
throw new HttpServerErrorException(HttpStatus.GATEWAY_TIMEOUT);
}
@GetMapping("/throw408")
public ResponseEntity<Void> throwResponseTimeout() {
throw new QueryTimeoutException();
}
@GetMapping("/throw500")
public ResponseEntity<Void> throwNotImplemented() {
throw new HttpServerErrorException(HttpStatus.NOT_IMPLEMENTED);
}
所以我通过运行我的应用程序进行测试,导航到 localhost:8080/throw408(我得到错误超时页面)、localhost:8080/throw500(我得到错误页面),这两个都是正确的。
然后我测试 localhost:8080/throw504 错误地打开错误页面,而不是我预期的错误超时。然后我测试 localhost:8080/jskld,它显示一个通用的 404 页面,而不是我预期的错误页面。
【问题讨论】:
-
请同时添加您对
HttpStatus.NOT_IMPLEMENTED的异常处理程序,因为您说它已经工作了 -
你检查过我下面的答案了吗?
标签: java spring spring-boot