原 Spring boot 自定义异常处理
版权声明:本文为博主原创文章,请尊重他人的劳动成果,转载请附上原文出处链接和本声明。
本文链接:https://www.91mszl.com/zhangwuji/article/details/1029
1 新建BusinessException 类
package com.mszl.candidate.exception;
public class BusinessException extends RuntimeException{
private static final long serialVersionUID = 1L;
// 自定义错误码
private Integer code;
// 自定义构造器,只保留一个,让其必须输入错误码及内容
public BusinessException(int code, String msg) {
super(msg);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
2 新建GlobalDefultExceptionHandler类
package com.mszl.candidate.exception;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.manulife.utils.BusinessUtils;
import com.manulife.utils.ReturnMsgUtils;
import lombok.extern.slf4j.Slf4j;
@ControllerAdvice
@Slf4j
public class GlobalDefultExceptionHandler {
//声明要捕获的异常
@ExceptionHandler(Exception.class)
@ResponseBody
public ReturnMsgUtils defultExcepitonHandler(HttpServletRequest request, Exception e) {
ReturnMsgUtils msg=null;
if(e instanceof BusinessException) {
BusinessException businessException = (BusinessException)e;
msg=new ReturnMsgUtils(businessException.getCode(), businessException.getMessage());
return msg;
} else{
Throwable t = e;
StringWriter stringWriter= new StringWriter();
PrintWriter writer= new PrintWriter(stringWriter);
t.printStackTrace(writer);
StringBuffer buffer= stringWriter.getBuffer();
log.error(buffer.toString());
msg = new ReturnMsgUtils(BusinessUtils.BUSINESS_CODE_201, BusinessUtils.BUSINESS_MSG_202,buffer.toString());
return msg;
}
}
}
3 到此就可以了。
2019-08-12 11:11:41 阅读(866)
名师出品,必属精品 https://www.91mszl.com
博主信息