统一异常处理

为了方便管理,把每个模块定义自己的异常类,如下


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;
    }
}

最近在整理一些资源工具,放在网站分享 http://tools.maqway.com
欢迎关注公众号:麻雀唯伊 , 不定时更新资源文章,生活优惠,或许有你想看的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值