• 基础组件-自定义异常和异常拦截


    自定义异常

    /**
     * @author: Gabriel
     * @date: 2020/1/17 14:56
     * @description 自定义异常
     */
    @Data
    public class BusinessException extends RuntimeException {
    
        /** 状态码 */
        protected int code;
    
        /** 错误信息 */
        protected String message;
    
        /** 枚举值 */
        private ResultCode resultCode;
    
    
        public BusinessException(ResultCode resultCode) {
            this.resultCode = resultCode;
            this.code = resultCode.getCode();
            this.message = resultCode.getDesc();
        }
    }

    异常拦截

    /**
     * @author: Gabriel
     * @date: 2020/1/17 14:55
     * @description 全局异常拦截
     */
    @Slf4j
    @RestControllerAdvice
    public class GlobalExceptionControllerAdvice {
    
        /**
         * 统一异常拦截
         * @param request
         * @param exception
         * @return
         */
        @ExceptionHandler(value = Exception.class)
        public Result exceptionHandler(HttpServletRequest request,Exception exception){
            /**
             * 如果是参数校验异常,不进入日志统计
             */
            if (exception instanceof BindException) {
                BindException e = (BindException) exception;
                List<ObjectError> allErrors = e.getAllErrors();
                String defaultMessage = allErrors.get(0).getDefaultMessage();
                return Result.errorCodeMessage(ResultCode.ILLEGAL_ARGUMENT.getCode(),defaultMessage);
            }
            /**
             * 非参数校验异常 记录日志 ,有助于错误排查
             */
            log.error("服务器内部错误: 请求地址--->{},请求ip--->:{},错误详情:{},请求参数:{}",
                    request.getRequestURL(), IpAddressUtil.getIpAddr(request), exception.getMessage(), RequestUtil.getParams(request));
    
            log.error("服务器内部请求异常",exception);
    
            if (exception instanceof BusinessException) {
                BusinessException e = (BusinessException) exception;
                return Result.response(e.getResultCode());
            }
    
            if (StringUtils.isBlank(exception.getMessage())) {
                return Result.errorCodeMessage(ResultCode.EXCEPTION.getCode(),"空指针异常");
            }
    
            return Result.errorCodeMessage(ResultCode.EXCEPTION.getCode(), exception.getMessage());
    
        }
    
    }
  • 相关阅读:
    欧拉函数模板
    Django Views Decorator
    Anaconda3 安装报错 bunzip2: command not found
    Windows 错误 0x80070570
    GitHub报错error: bad signature
    failed to push some refs to 'git@github.com:RocsSun/mytest.git
    更新GitHub的仓库
    Git连接GitHub
    Git的初始化设置
    Git的选项参数
  • 原文地址:https://www.cnblogs.com/july-sunny/p/12240210.html
Copyright © 2020-2023  润新知