SpringBoot项目全局异常处理

一.为什么要配置全局异常?
     不配置全局异常,服务端报错场景 1/0、空指针等
二.配置好处  
     统⼀的错误页面或者错误码
     对用户更友好
 三.Springboot2.X怎么在项⽬中配置全局异常?
     类添加注解:
           @ControllerAdvice,如果需要返回json数据,则方法需要加@ResponseBody
           @RestControllerAdvice, 默认返回json数据,方法不需要加@ResponseBody
     方法添加处理器
     捕获全局异常,处理所有不可知的异常
         @ExceptionHandler(value=Exception.class)
package com.example.online_xdclass.Exception;

import com.example.online_xdclass.Utils.JsonData;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常处理类
 */
@ControllerAdvice
public class ExceptionHandler {
   // private final static Logger logger= LoggerFactory.getLogger(ExceptionHandler.class);
    @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonData handler(Exception e){
        //logger.error("[系统异常]{}",e);
        if(e instanceof XDException){
            XDException xdException=(XDException) e;
            return JsonData.buildError(xdException.getCode(),xdException.getMsg());
        }
        else{
            return JsonData.buildError("全局异常,未知错误!");
        }
    }
}

   自定义异常类

package com.example.online_xdclass.Exception;

/**
 * 自定义异常类,关键是在于继承什么类自定义就是什么异常
 */
public class XDException extends RuntimeException{
    private Integer code;
    private String msg;
    public XDException(Integer code,String msg){
        this.code=code;
        this.msg=msg;
    }

    public Integer getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public String toString() {
        return "XDException{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                '}';
    }
}

 

 

posted @ 2021-06-30 15:48  Allen-LuoYi  阅读(98)  评论(0)    收藏  举报