GlobalException.java 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package com.pj.project4sp.global;
  2. import java.sql.SQLException;
  3. import org.springframework.data.redis.RedisConnectionFailureException;
  4. import org.springframework.web.bind.annotation.ControllerAdvice;
  5. import org.springframework.web.bind.annotation.ExceptionHandler;
  6. import org.springframework.web.bind.annotation.ResponseBody;
  7. import com.pj.project4sp.apilog.SpApilogUtil;
  8. import com.pj.project4sp.spcfg.SpCfgUtil;
  9. import com.pj.utils.sg.AjaxError;
  10. import com.pj.utils.sg.AjaxJson;
  11. import cn.dev33.satoken.exception.NotLoginException;
  12. import cn.dev33.satoken.exception.NotPermissionException;
  13. /**
  14. * 全局异常拦截
  15. * <p> @ControllerAdvice 可指定包前缀,例如:(basePackages = "com.pj.controller.admin")
  16. * @author kong
  17. *
  18. */
  19. @ControllerAdvice
  20. public class GlobalException {
  21. /** 全局异常拦截 */
  22. @ResponseBody
  23. @ExceptionHandler
  24. public AjaxJson handlerException(Exception e) {
  25. // 打印堆栈,以供调试
  26. e.printStackTrace();
  27. // 记录日志信息
  28. AjaxJson aj = null;
  29. Throwable e2 = e.getCause();
  30. // ------------- 判断异常类型,提供个性化提示信息
  31. if (e instanceof BusinessException){
  32. aj=AjaxJson.getError(e.getMessage());
  33. }
  34. // 如果是未登录异常
  35. else if(e instanceof NotLoginException){
  36. aj = AjaxJson.getNotLogin();
  37. }
  38. // 如果是权限异常
  39. else if(e instanceof NotPermissionException) {
  40. NotPermissionException ee = (NotPermissionException) e;
  41. aj = AjaxJson.getNotJur("无此权限:" + ee.getCode());
  42. }
  43. // 如果是AjaxError,则获取其具体code码
  44. else if(e instanceof AjaxError) {
  45. AjaxError ee = (AjaxError) e;
  46. aj = AjaxJson.get(ee.getCode(), ee.getMessage());
  47. }
  48. // 如果是SQLException,并且指定了hideSql,则只返回sql error
  49. else if((e instanceof SQLException || e2 instanceof SQLException) && SpCfgUtil.throwOutSql() == false) {
  50. // 无论是否打开隐藏sql,日志表记录的都是真实异常信息
  51. aj = AjaxJson.getError(e2.getMessage());
  52. SpApilogUtil.endRequest(aj);
  53. return AjaxJson.getError("Sql Error").set("reqId", SpApilogUtil.getCurrReqId());
  54. }
  55. // 如果是redis连接异常 ( 由于redis连接异常,系统已经无法正常工作,所以此处需要立即返回 )
  56. else if(e instanceof RedisConnectionFailureException) {
  57. aj = AjaxJson.getError("Redis异常,请检查连接信息");
  58. aj.set("reqId", SpApilogUtil.getCurrReqId());
  59. return aj;
  60. }
  61. // 普通异常输出:500 + 异常信息
  62. else {
  63. aj = AjaxJson.getError(e.getMessage());
  64. }
  65. // 插入到日志表
  66. SpApilogUtil.endRequest(aj);
  67. // 返回到前台
  68. aj.set("reqId", SpApilogUtil.getCurrReqId());
  69. return aj;
  70. }
  71. }