package cn.zkhh.controller;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.zkhh.utils.constants.CommonUtil;
import cn.zkhh.utils.constants.ErrorEnum;
import com.alibaba.fastjson.JSONObject;
/**
* 全局拦截异常
* @description
* @Created by jyy on 2019年1月20日
* @version 1.0.0
*/
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler02 {
/**
* 权限不足报错拦截
*
* @return
* @throws Exception
*/
@ExceptionHandler(UnauthorizedException.class)
public JSONObject unauthorizedExceptionHandler() throws Exception {
return CommonUtil.errorJson(ErrorEnum.E_502);
}
/**
* 未登录报错拦截
* 在请求需要权限的接口,而连登录都还没登录的时候,会报此错
*
* @return
* @throws Exception
*/
@ExceptionHandler(UnauthenticatedException.class)
public JSONObject unauthenticatedException() throws Exception {
return CommonUtil.errorJson(ErrorEnum.E_20011);
}
/**
* GET/POST请求方法错误的拦截器
* 因为开发时可能比较常见,而且发生在进入controller之前,上面的拦截器拦截不到这个错误
* 所以定义了这个拦截器
*
* @return
* @throws Exception
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public JSONObject httpRequestMethodHandler() throws Exception {
return CommonUtil.errorJson(ErrorEnum.E_500);
}
}
异常实体
package cn.zkhh.utils.constants;
/**
* @author: jyy
* @date: 2017/10/24 10:16
*/
public enum ErrorEnum {
/*
* 错误信息
* */
E_400("400", "请求处理异常,请稍后再试"),
E_500("500", "请求方式有误,请检查 GET/POST"),
E_501("501", "请求路径不存在"),
E_502("502", "对不起,您拥有的角色权限不足!"),
E_10008("10008", "角色删除失败,尚有用户属于此角色"),
E_10009("10009", "账户已存在"),
E_10010("10010", "单位已存在"),
E_10011("10011", "部门已存在"),
E_10012("10012", "该经济科目已存在,请重新添加!"),
E_20011("20011", "登陆已过期,请重新登陆"),
E_90003("90003", "缺少必填参数");
private String errorCode;
private String errorMsg;
ErrorEnum() {
}
ErrorEnum(String errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}