zoukankan      html  css  js  c++  java
  • Java自定义异常类以及异常拦截器

      自定义异常类不难,但下面这个方法,它的核心是异常拦截器类。
      就算是在分布式系统间进行传递也可以,只要最顶层的服务有这个异常拦截器类(下例是在 springboot 项目中)

    1、自定义异常类,继承自 RuntimeException,参数只有一个异常错误码

    public class BingException extends RuntimeException {
        private final int code;
    
        public BingException(int code) {
            this.code = code;
        }
    
        public int getCode() {
            return this.code;
        }
    
        public String getMessage() {
            return this.toString();
        }
    
        public String toString() {
            return "系统异常,异常编码:" + this.code;
        }
    }

    2、异常拦截器类 

    package cn.jiashubing.config;
    
    import cn.jiashubing.common.BingException;
    import cn.jiashubing.result.ResultModel;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    /**
     * @author jiashubing
     * @since 2019/6/17
     */
    @ControllerAdvice
    public class BingExceptionHandler {
    
        //自定义异常返回对应编码
        @ExceptionHandler(BingException.class)
        @ResponseBody
        public ResultModel handlerBingException(BingException e) {
            return new ResultModel(false, "token_outtime");
        }
    
        //其他异常报对应的信息
        @ExceptionHandler(Exception.class)
        @ResponseBody
        public ResultModel handlerSellException(Exception e) {
            return new ResultModel(false, "系统出错,错误信息为:" + e.getMessage());
        }
    
    }

      

    也可以用下面复杂一点的办法

    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;
    
    /**
     * @author jiashubing
     * @since 2018/10/29
     */
    @ControllerAdvice
    public class ExceptionHandle {
    
        private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
    
        /**
         * 异常处理
         * @param e 异常信息
         * @return 返回类是我自定义的接口返回类,参数是返回码和返回结果,异常的返回结果为空字符串
         */
        @ExceptionHandler(value = Exception.class)
        @ResponseBody
        public Result handle(Exception e) {
            //自定义异常返回对应编码
            if (e instanceof BingException) {
                BingException ex = (BingException) e;
                return new Result<>(ex.getCode(), "");
            }
            //其他异常报对应的信息
            else {
                logger.info("[系统异常]{}", e.getMessage(), e);
                return new Result<>(-1, "");
            }
    
        }
    }

    PS:还可以返回不同的response 状态,默认是200,@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 这个是返回500状态

    3、然后在代码里抛异常就可以直接抛出异常了

    throw new BingException(5);

    原创文章,欢迎转载,转载请注明出处!

  • 相关阅读:
    RecyclerView 数据刷新的几种方式 局部刷新 notify MD
    【图片】批量获取几万张图片
    RV BaseRecyclerViewAdapterHelper 总结 MD
    RecyclerView.ItemDecoration 间隔线
    Kotlin【简介】Android开发 配置 扩展
    Kotlin 特性 语法糖 优势 扩展 高阶 MD
    一个十分简洁实用的MD风格的UI主框架
    折叠伸缩工具栏 CollapsingToolbarLayout
    FloatingActionButton FAB 悬浮按钮
    Glide Picasso Fresco UIL 图片框架 缓存 MD
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/java_exception.html
Copyright © 2011-2022 走看看