一、使用注解@ControllerAdvice 对Controller 增强,创建全局异常处理类
import com.kejiang.qyzbt.bffc.enums.ErrorResultEnum;
import com.ocean.common.dto.ApiResponse;
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 javax.servlet.http.HttpServletRequest;
/**
* controller 层异常捕获统一处理
* @author 作者 E-mail: songfz
* @version 1.0
* @date 创建时间:2018年7月10日 下午3:55:32
* @parameter
* @return
* @since
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 系统异常处理,比如:404,500
*
* @param req
* @param e
* @return
* @throws Exception
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ApiResponse<?> defaultErrorHandler(HttpServletRequest req, Exception e){
logger.error("异常:" + e.getMessage(), e);
ApiResponse baseResp = new ApiResponse();
baseResp.setMsg(e.getMessage());
if (e instanceof ExecuteException) {
baseResp.setCode(ErrorResultEnum.getCode(e.getMessage()));
} else {
baseResp.setCode(ErrorResultEnum.FAIL.getCode());
}
return baseResp;
}
}
二、自定义异常对象
public class ExecuteException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public ExecuteException() {
super();
}
public ExecuteException(String message) {
super();
this.message = message;
}
}
三 controller层 不捕获异常向上抛出异常
网友评论