Spring-Boot程序员SpringBoot极简教程 · Spring Boot

SpringBoot Web统一异常处理

2019-03-05  本文已影响4人  一曲畔上

SpringBoot项目中,常规的Web异常一般处理方式是添加一个统一异常处理类,比如

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger("WEB.LOG");
    
    /**
     * NullPointerException异常处理
     * @param ex NullPointerException
     * @return 返回结果
     */
    @ExceptionHandler(value = NullPointerException.class)
    public ReturnResult<Object> nullPointerExceptionHandler(NullPointerException ex) {
        ResultEnum resultEnu = ResultEnum.SYS_ERROR;
        
        String errorMsg = "NullPointerException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, null);
    }
    ...
}

但是,这里有个比较棘手的问题就是404错误,通过这种方式直接是无法捕获到的!
好在SpringBoot提供了一种解决方案:默认情况下提供了一个/error处理器。
如果你配置了该处理器,那么他会按照你的配置执行,如果没配置,那么或抛出一个如下的异常结果

{
    "timestamp": "2019-03-05 22:20:54",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/phoenix/mountain/v1/demo/5"
}

这个结果与我们想要的返回结果可能不一致,那怎么办呢?
方案一,对/error处理器定制,返回我们预期的结果;
但这种处理方案会导致异常处理被割裂开来,不能达到统一处理异常。
方案二,我们也是对/error处理器定制,但是不直接返回结果,而是抛出一个异常,如下

@RestController
public class DefaultErrorController {
    @RequestMapping(value = {"/error"}, method = {RequestMethod.GET})
    public void error(HttpServletRequest request, HttpServletResponse response) throws NoHandlerFoundException {
        Object obj = request.getAttribute("javax.servlet.error.request_uri");
        String errorUrl = obj == null? null : obj.toString();
        
        throw new NoHandlerFoundException(request.getMethod(), errorUrl, new HttpHeaders());
    }
}

此时,我们便可以在GlobalExceptionHandler处理器中捕获NoHandlerFoundException,进行统一处理:

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger("WEB.LOG");
    
    /**
     * NullPointerException异常处理
     * @param ex NullPointerException
     * @return 返回结果
     */
    @ExceptionHandler(value = NullPointerException.class)
    public ReturnResult<Object> nullPointerExceptionHandler(NullPointerException ex) {
        ResultEnum resultEnu = ResultEnum.SYS_ERROR;
        
        String errorMsg = "NullPointerException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, null);
    }
        /**
     * NoHandlerFoundException(404)异常处理
     * @param ex NoHandlerFoundException
     * @return 返回结果
     */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ReturnResult<Object> noHandlerFoundExceptionHandler(NoHandlerFoundException ex) {
        ResultEnum resultEnu = ResultEnum.PATH_NOT_FOUND;
        
        String errorMsg = "NoHandlerFoundException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, ex.getRequestURL());
    }
    ...
}

一个完整的Web统一异常处理器如下

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger("WEB.LOG");
    
    /**
     * NullPointerException异常处理
     * @param ex NullPointerException
     * @return 返回结果
     */
    @ExceptionHandler(value = NullPointerException.class)
    public ReturnResult<Object> nullPointerExceptionHandler(NullPointerException ex) {
        ResultEnum resultEnu = ResultEnum.SYS_ERROR;
        
        String errorMsg = "NullPointerException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, null);
    }
    
    /**
     * ClassCastException异常处理
     * @param ex ClassCastException
     * @return 返回结果
     */
    @ExceptionHandler(value = ClassCastException.class)
    public ReturnResult<Object> classCastExceptionHandler(ClassCastException ex) {
        ResultEnum resultEnu = ResultEnum.SYS_ERROR;
        
        String errorMsg = "ClassCastException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, null);
    }
    
    /**
     * IOException异常处理
     * @param ex IOException
     * @return 返回结果
     */
    @ExceptionHandler(value = IOException.class)
    public ReturnResult<Object> ioExceptionHandler(IOException ex) {
        ResultEnum resultEnu = ResultEnum.SYS_ERROR;
        
        String errorMsg = "IOException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, null);
    }
    
    /**
     * NoSuchMethodException异常处理
     * @param ex NoSuchMethodException
     * @return 返回结果
     */
    @ExceptionHandler(value = NoSuchMethodException.class)
    public ReturnResult<Object> noSuchMethodExceptionHandler(NoSuchMethodException ex) {
        ResultEnum resultEnu = ResultEnum.SYS_ERROR;
        
        String errorMsg = "NoSuchMethodException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, null);
    }
    
    /**
     * IndexOutOfBoundsException异常处理
     * @param ex IndexOutOfBoundsException
     * @return 返回结果
     */
    @ExceptionHandler(value = IndexOutOfBoundsException.class)
    public ReturnResult<Object> indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
        ResultEnum resultEnu = ResultEnum.SYS_ERROR;
        
        String errorMsg = "IndexOutOfBoundsException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, null);
    }
    
    /**
     * HttpMessageNotReadableException(404)异常处理
     * @param ex HttpMessageNotReadableException
     * @return 返回结果
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public ReturnResult<Object> httpMessageNotReadableExceptionHandler(HttpMessageNotReadableException ex) {
        ResultEnum resultEnu = ResultEnum.PATH_NOT_FOUND;
        
        String errorMsg = "HttpMessageNotReadableException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, null);
    }
    
    /**
     * NoHandlerFoundException(404)异常处理
     * @param ex NoHandlerFoundException
     * @return 返回结果
     */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ReturnResult<Object> noHandlerFoundExceptionHandler(NoHandlerFoundException ex) {
        ResultEnum resultEnu = ResultEnum.PATH_NOT_FOUND;
        
        String errorMsg = "NoHandlerFoundException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, ex.getRequestURL());
    }
    
    /**
     * HttpRequestMethodNotSupportedException(405)异常处理
     * @param ex HttpRequestMethodNotSupportedException
     * @return 返回结果
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public ReturnResult<Object> httpRequestMethodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException ex) {
        ResultEnum resultEnu = ResultEnum.PARAM_ERROR;
        
        String errorMsg = "HttpRequestMethodNotSupportedException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, ex.getMethod());
    }
    
    /**
     * HttpMediaTypeNotAcceptableException(406)异常处理
     * @param ex HttpMediaTypeNotAcceptableException
     * @return 返回结果
     */
    @ExceptionHandler(value = HttpMediaTypeNotAcceptableException.class)
    public ReturnResult<Object> httpMediaTypeNotAcceptableExceptionHandler(HttpMediaTypeNotAcceptableException ex) {
        ResultEnum resultEnu = ResultEnum.PARAM_ERROR;
        
        String errorMsg = "HttpMediaTypeNotAcceptableException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, ex.getSupportedMediaTypes());
    }
    
    /**
     * MethodArgumentNotValidException异常处理
     * @param ex MethodArgumentNotValidException
     * @return 返回结果
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ReturnResult<Object> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException ex) {
        ResultEnum resultEnu = ResultEnum.PARAM_ERROR;
        
        String errorMsg = "MethodArgumentNotValidException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, ex.getParameter());
    }
    
    /**
     * ConstraintViolationException异常处理
     * @param ex ConstraintViolationException
     * @return 返回结果
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ReturnResult<Object> constraintViolationExceptionHandler(ConstraintViolationException ex) {
        ResultEnum resultEnu = ResultEnum.PARAM_ERROR;
        
        String errorMsg = "ConstraintViolationException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, ex.getConstraintViolations());
    }
    
    /**
     * WdRuntimeException异常处理
     * @param ex WdRuntimeException
     * @return 返回结果
     */
    @ExceptionHandler(value = WdRuntimeException.class)
    public ReturnResult<Object> wdRuntimeExceptionHandler(WdRuntimeException ex) {
        ResultEnum resultEnu = ResultEnum.FAILURE;
        
        String errorMsg = "WdRuntimeException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, ex.getDesc());
    }
    
    /**
     * RuntimeException异常处理
     * @param ex RuntimeException
     * @return 返回结果
     */
    @ExceptionHandler(value = RuntimeException.class)
    public ReturnResult<Object> runtimeExceptionHandler(RuntimeException ex) {
        ResultEnum resultEnu = ResultEnum.SYS_ERROR;
        
        String errorMsg = "RuntimeException Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, null);
    }
    
    /**
     * Exception异常处理
     * @param ex Exception
     * @return 返回结果
     */
    @ExceptionHandler(value = Exception.class)
    public ReturnResult<Object> otherExceptionHandler(Exception ex) {
        ResultEnum resultEnu = ResultEnum.FAILURE;
        
        String errorMsg = "Exception Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, null);
    }
    
    /**
     * Throwable异常处理
     * @param ex Throwable
     * @return 返回结果
     */
    @ExceptionHandler(value = Throwable.class)
    public ReturnResult<Object> otherThrowableHandler(Throwable ex) {
        ResultEnum resultEnu = ResultEnum.FAILURE;
        
        String errorMsg = "Throwable Error!";
        
        return exceptionHandler(resultEnu, errorMsg, ex, null);
    }
    
    /**
     * +统一异常处理
     * @param resultEnu
     * @return
     */
    private ReturnResult<Object> exceptionHandler(ResultEnum resultEnu, String errorMsg, Throwable th, Object entry) {
        writeErrorLog(errorMsg, th);
        
        return new ReturnResult<Object>(resultEnu.getCode(), resultEnu.getDesc(), entry);
    }
    
    /**
     * 错误日志输出
     * @param message 日志内容
     * @param t 异常
     */
    public void writeErrorLog(final String message, final Throwable t) {
        if (logger.isErrorEnabled()) {
            logger.error(message, t);
        }
    }

    /**
     * 错误日志输出
     * @param message 日志内容
     */
    public void writeErrorLog(final String message) {
        if (logger.isErrorEnabled()) {
            logger.error(message);
        }
    }
}

-End-

上一篇下一篇

猜你喜欢

热点阅读