Spring异常集中处理和日志集中打印

使用@ControllerAdvice和@ExceptionHandler处理Controller层的异常:

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理所有不可知的异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    AppResponse handleException(Exception e){
        // 记录日志
        LOGGER.error(e.getMessage(), e);
        // 统一返回值
        AppResponse response = new AppResponse();
        response.setFail("服务器错误");
        return response;
    }

    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    AppResponse handleCustomException(CustomException e){
        LOGGER.error(e.getMessage(), e);

        AppResponse response = new AppResponse();
        response.setFail(e.getMessage());
        return response;
    }
}

 对于需要给前台返回特定错误信息的异常,手动抛出CustomException,并添加错误信息,通过handleCustomException返回,其他异常信息通过handleException处理,返回服务器异常,所有异常均打印日志

 

posted on 2019-06-23 23:50  Jong_L  阅读(684)  评论(0编辑  收藏  举报

导航