47 lines
1.8 KiB
Markdown
47 lines
1.8 KiB
Markdown
|
# 统一处理异常
|
|||
|
|
|||
|
---
|
|||
|
|
|||
|
首先 SpringBoot 自动对我们的异常做了一个**表面处理**,我们只要遵守它的约定:
|
|||
|
|
|||
|
- 以错误码命名文件,放在 `/templates/error` 文件夹下即可
|
|||
|
|
|||
|
<img src="https://gitee.com/veal98/images/raw/master/img/20210125103620.png" style="zoom: 67%;" />
|
|||
|
|
|||
|
当然,这种处理仅仅是页面的跳转,对用户来说相对友好,但是对于开发者来说并没有啥用,500 出现的原因是服务端错误,我们需要对出错的具体原因进行一个统一的日志记录
|
|||
|
|
|||
|
![](https://gitee.com/veal98/images/raw/master/img/20210125104538.png)
|
|||
|
|
|||
|
```java
|
|||
|
/**
|
|||
|
* 处理服务端异常(500)
|
|||
|
*/
|
|||
|
@ControllerAdvice(annotations = Controller.class) // 扫描带有 @Controller 的组件
|
|||
|
public class ExceptionAdvice {
|
|||
|
|
|||
|
private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
|
|||
|
|
|||
|
@ExceptionHandler({Exception.class})
|
|||
|
public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
|
|||
|
logger.error("服务器发生异常:" + e.getMessage());
|
|||
|
for (StackTraceElement element : e.getStackTrace()) {
|
|||
|
logger.error(element.toString());
|
|||
|
}
|
|||
|
// 区分异步请求和普通请求
|
|||
|
String xRequestedWith = request.getHeader("x-requested-with");
|
|||
|
if ("XMLHttpRequest".equals(xRequestedWith)) {
|
|||
|
// 异步请求(希望返回的是 JSON 数据)
|
|||
|
response.setContentType("application/plain;charset=utf-8");
|
|||
|
PrintWriter writer = response.getWriter();
|
|||
|
writer.write(CommunityUtil.getJSONString(1, "服务器异常"));
|
|||
|
}
|
|||
|
else {
|
|||
|
// 普通请求(希望返回的是一个网页)
|
|||
|
response.sendRedirect(request.getContextPath() + "/error");
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
```
|
|||
|
|