統一異常處理

爲了方便管理,把每個模塊定義自己的異常類,如下


import com.maqway.wxht.Enums.ResultEnum;

/**
 * @author: Ma.li.ran
 * @datetime: 2017/12/26 14:54
 * @desc: 用戶異常
 * @environment: jdk1.8.0_121/IDEA 2017.2.6/Tomcat8.0.47/mysql5.7
 */
public class UserOperationException extends RuntimeException{

  private int state;//異常碼

  public UserOperationException(int state,String msg) {
    super(msg);//異常信息
    this.state =state;
  }

  public int getState() {
    return state;
  }

  public void setState(int state) {
    this.state = state;
  }
}

然後定義全局異常攔截器,當拋出異常時進入


import com.maqway.wxht.Enums.ResultEnum;
import com.maqway.wxht.Exception.UserOperationException;
import com.maqway.wxht.dto.Execution.Result;
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
/**
 * 統一異常處理
 * Created by Ma.li.ran on 2017/09/23 17:14
 */
@ControllerAdvice
@ResponseBody
public class ExceptionHandle {

    private final static Logger logger  = LoggerFactory.getLogger(ExceptionHandle.class);
    @ExceptionHandler(value = Exception.class)
    public Map<String,Object> handle(Exception e) {
            Map<String,Object> modelMap = new HashMap<>();
            if(e instanceof 你的異常){
            //自己處理的邏輯
            }
            logger.info(e.getClass()+"{}",printMessaege(e));
              modelMap.put("success",false);
              modelMap.put("errCode",ResultEnum.ERROR.getState());//ResultEnum是對錯誤信息的枚舉類
              modelMap.put("errMsg",ResultEnum.ERROR.getStateInfo());
            return modelMap;

    }

    public String printMessaege(Exception e) {
        String message = null;
        String messages = null;
        StackTraceElement[] st = e.getStackTrace();
        for (int i = 0; i < st.length; i++) {
            message = st[i].getFileName() + "文件" + "\t" + st[i].getClassName()
                + "類\t" + st[i].getMethodName() + "方法\t"
                + st[i].getLineNumber() + "行發生"+"異常\n"+e.getMessage();
            messages += message;
        }
        return message;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章