2020-02-05 00:31:51 +08:00
|
|
|
|
package com.pj.test;
|
|
|
|
|
|
|
|
|
|
import java.io.IOException;
|
|
|
|
|
|
|
|
|
|
import javax.servlet.http.HttpServletRequest;
|
|
|
|
|
import javax.servlet.http.HttpServletResponse;
|
|
|
|
|
|
|
|
|
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
|
|
|
import org.springframework.web.bind.annotation.ModelAttribute;
|
2020-10-13 16:11:06 +08:00
|
|
|
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
2020-02-05 00:31:51 +08:00
|
|
|
|
|
|
|
|
|
import cn.dev33.satoken.exception.NotLoginException;
|
|
|
|
|
import cn.dev33.satoken.exception.NotPermissionException;
|
|
|
|
|
|
|
|
|
|
/**
|
2020-06-15 22:03:41 +08:00
|
|
|
|
* 全局异常处理
|
2020-02-05 00:31:51 +08:00
|
|
|
|
*/
|
2020-10-13 16:11:06 +08:00
|
|
|
|
@RestControllerAdvice // 可指定包前缀,比如:(basePackages = "com.pj.admin")
|
2020-06-15 22:03:41 +08:00
|
|
|
|
public class GlobalException {
|
2020-02-05 00:31:51 +08:00
|
|
|
|
|
|
|
|
|
// 在每个控制器之前触发的操作
|
|
|
|
|
@ModelAttribute
|
|
|
|
|
public void get(HttpServletRequest request) throws IOException {
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 全局异常拦截(拦截项目中的所有异常)
|
|
|
|
|
@ExceptionHandler
|
2020-06-15 22:03:41 +08:00
|
|
|
|
public AjaxJson handlerException(Exception e, HttpServletRequest request, HttpServletResponse response)
|
2020-02-05 00:31:51 +08:00
|
|
|
|
throws Exception {
|
|
|
|
|
|
2020-05-02 15:19:55 +08:00
|
|
|
|
// 打印堆栈,以供调试
|
|
|
|
|
e.printStackTrace();
|
2020-02-05 00:31:51 +08:00
|
|
|
|
|
2020-05-02 15:19:55 +08:00
|
|
|
|
// 不同异常返回不同状态码
|
|
|
|
|
AjaxJson aj = null;
|
|
|
|
|
if (e instanceof NotLoginException) { // 如果是未登录异常
|
|
|
|
|
aj = AjaxJson.getNotLogin();
|
|
|
|
|
} else if(e instanceof NotPermissionException) { // 如果是权限异常
|
2020-02-05 00:31:51 +08:00
|
|
|
|
NotPermissionException ee = (NotPermissionException) e;
|
2020-05-02 15:19:55 +08:00
|
|
|
|
aj = AjaxJson.getNotJur("无此权限:" + ee.getCode());
|
|
|
|
|
} else { // 普通异常, 输出:500 + 异常信息
|
|
|
|
|
aj = AjaxJson.getError(e.getMessage());
|
2020-02-05 00:31:51 +08:00
|
|
|
|
}
|
2020-06-15 22:03:41 +08:00
|
|
|
|
|
|
|
|
|
// 返回给前端
|
|
|
|
|
return aj;
|
2020-02-05 00:31:51 +08:00
|
|
|
|
|
2020-05-02 15:19:55 +08:00
|
|
|
|
// 输出到客户端
|
2020-06-15 22:03:41 +08:00
|
|
|
|
// response.setContentType("application/json; charset=utf-8"); // http说明,我要返回JSON对象
|
|
|
|
|
// response.getWriter().print(new ObjectMapper().writeValueAsString(aj));
|
2020-02-05 00:31:51 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|