springboot如何全局捕捉异常
解决方法:
下面的@ExceptionHandler(Exception.class)表示捕捉没有在代码中try catch的异常
@ExceptionHandler(SurvetException.class)表示只捕捉自定义的异常,SurvetException是我自定义的继承Exception的类,如果执行了@ExceptionHandler(SurvetException.class)中的代码就不再执行@ExceptionHandler(Exception.class)中的代码
import com.alibaba.fastjson.JSON;
import com.thinkcc.survet.base.utils.RspStatusAndMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@ControllerAdvice
public class GrobalExceptionHandler {
private static Logger log= LoggerFactory.getLogger(GrobalExceptionHandler.class);
@ExceptionHandler(SurvetException.class)
@ResponseBody
public RspStatusAndMsg grobalExceptionHandler(HttpServletRequest request, SurvetException ex) {
RspStatusAndMsg rspStatusAndMsg = new RspStatusAndMsg();
if (ex.getErrorCode() == null) {
rspStatusAndMsg.setErrorCode("10009");
} else {
rspStatusAndMsg.setErrorCode(ex.getErrorCode());
}
rspStatusAndMsg.setMessage(ex.getMessage());
rspStatusAndMsg.setStatus(false);
return rspStatusAndMsg;
}
@ExceptionHandler(Exception.class)
@ResponseBody
public RspStatusAndMsg BindExceptionHandler(HttpServletRequest request, Exception ex) {
RspStatusAndMsg rspStatusAndMsg = new RspStatusAndMsg();
rspStatusAndMsg.setErrorCode(500);
rspStatusAndMsg.setMessage("服务忙,请稍后重试");
rspStatusAndMsg.setStatus(false);
log.error(ex.getMessage(),ex);
if (log.isDebugEnabled()){
ex.printStackTrace();
}
return rspStatusAndMsg;
}
}