91名师指路-头部
91名师指路

Spring boot 自定义异常处理

由于某些原因,现在不支持支付宝支付,如需要购买源码请加博主微信进行购买,微信号:13248254750

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     阅读(869)

名师出品,必属精品    https://www.91mszl.com

联系博主    
用户登录遮罩层
x

账号登录

91名师指路-底部