【发布时间】:2016-08-29 10:07:05
【问题描述】:
我需要一个控制器(或其他组件)来处理所有 404 错误并巧妙地重定向到正确的页面(这基于表 src/ 目标)。我发现了一些关于处理 FROM 控制器抛出的异常的问题,所以我做了以下几点:
@ControllerAdvice
public class ServiceExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Throwable.class)
@ResponseBody
ResponseEntity<String> handleControllerException(HttpServletRequest req, Throwable ex) {
String slug = req.getRequestURI(); // this is the URL that was not found
URI location=null;
try {
// lookup based on slug ...
location = new URI("http://cnn.com"); // let's say I want to redirect to cnn
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setLocation(location);
return new ResponseEntity<String>("Page has permanently moved", responseHeaders, HttpStatus.PERMANENT_REDIRECT);
}
}
我没有进行任何其他配置更改
这有两个问题:
- 它只捕获我的其他控制器抛出的异常,而不是 404 错误
- 它捕获所有类型的异常,而不仅仅是 404
关于如何实现一种“包罗万象”的任何想法?
【问题讨论】:
标签: spring spring-mvc error-handling spring-boot http-status-code-404