zoukankan      html  css  js  c++  java
  • (入门SpringBoot)SpringBoot配置全局异常(五)

    Spring的全局异常,用于捕获程序员没有捕获的异常。具体请看下面代码:

    1.ControllerAdvice拦截异常,统一处理.通过Spring的AOP来管理.

    @ControllerAdvice
    public class ExceptionHandle {

        /**
         * 要捕获什么异常:
         * @return 返回Result:
         */
        @ExceptionHandler(value = Exception.class)
        @ResponseBody
        public Result handle(Exception e){
            e.printStackTrace();
            if(e instanceof MyException){
                MyException myException = (MyException)e;
                return ResultUtil.error(myException.getCode(),myException.getMessage());
            }else{
                return ResultUtil.error(-1,"系统错误,请联系程序员");
            }
        }


    }

    1. 因为原来的Exception只可以传msg,那么我们就可以自定义自己的异常,可以传code:


    /**
     * 自定义异常类,因为Exception抛出只可以传消息,太不方便了.
     *        提示:RuntimeException, 源码:RuntimeException extends Exception
     *            并且Spring框架对RuntimeException才会回滚.Exception不会回滚.
     * create by xxx

     * 2019-05-26
     */
    public class MyException extends RuntimeException {

        private Integer code;

        public MyException(ResultEnum resultEnum){
            super(resultEnum.getMsg());//父类可以穿个msg,Service层可以抛出MyException.
            this.code = resultEnum.getCode();
        }

        public Integer getCode() {
            return code;
        }

        public void setCode(Integer code) {
            this.code = code;
        }
    }

    1. 因为现在的项目有一些会返回code信息,但是随手定义一个不好维护,我们可以定义成枚举类型,对这些code,msg进行统一管理.

    /**
     * created by : xxx

     * 2019-05-27
     */
    public enum  ResultEnum {
        UNCO_ERROR(-1,"未知错误"),
        SUCCESS(0,"成功")
        ;
        /**
         * 编码:
         */
        private Integer code;
        /**
         * 消息:
         */
        private String msg;

        ResultEnum(Integer code,String msg){
            this.code = code;
            this.msg = msg;
        }

        public Integer getCode() {
            return code;
        }

        public String getMsg() {
            return msg;
        }
    }

  • 相关阅读:
    浅谈LBS(基于位置的服务)
    MapBar地图更新啦
    推荐一款软件:Global Mapper
    51ditu、清华地图以及Google地图
    极索(Gsuo)推出新版地图采用Gmap设计思路
    公告:Rover's Official Blog停止更新
    最后的礼物:校园多媒体系统和校园WEBGIS系统
    JAVA中最常用的十个快捷键
    启程去旅行 android之merge布局 http://www.cnblogs.com/travelfromandroid/articles/2133206.html
    Http 范例
  • 原文地址:https://www.cnblogs.com/historylyt/p/10928729.html
Copyright © 2011-2022 走看看