为了方便管理,把每个模块定义自己的异常类,如下
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
欢迎关注公众号:麻雀唯伊 , 不定时更新资源文章,生活优惠,或许有你想看的