springboot全局异常处理类
时间:2024-5-15 16:24 作者:紫琪软件工作室 分类: 配置
注:BusinessException.class 为自定义异常类,替换为需要处理的异常信息类即可
import lombok.extern.slf4j.Slf4j;
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;
/**
* 全局异常处理
* @author ZhangJi
*/
@ControllerAdvice
@Slf4j
public class DefaultExceptionHandler {
@ExceptionHandler(BusinessException.class)
public Object handleException(BusinessException e, HttpServletRequest request){
log.error("请求:{}发生异常", request.getRequestURI());
log.error("异常信息:{}", e.getMessage());
Result result = new Result();
result.setSuccess(false);
result.setCode(e.getExcpCode());
result.setMsg(e.getMessage());
log.error(result.toJsonString());
return result;
}
@ExceptionHandler(Exception.class)
public Object handleException(Exception e, HttpServletRequest request){
log.error("请求:{}发生异常", request.getRequestURI());
log.error("异常信息:{}", e.getMessage());
Result result = new Result();
result.setSuccess(false);
if (e instanceof BusinessException) {
result.setCode(((BusinessException) e).getExcpCode());
result.setMsg(e.getMessage());
} else {
result.setCode(DefaultExceptionEnum.OTHER_ERROR.getCode());
result.setMsg(DefaultExceptionEnum.OTHER_ERROR.getMsg());
}
log.error(result.toJsonString());
return result;
}
}