日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

SpringBoot 全局異常處理

作者:生產隊的驢. 更新時間: 2024-02-16 編程語言

介紹

如果代碼沒有做異常處理,就會報框架錯誤,而這種格式不符合REST風格,也可以在每一個接口添加 try{ } catch { } 捕獲異常,但是會非常的繁瑣,這時候可以使用全局異常處理。
在這里插入圖片描述

統一響應類

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
    Integer code;
    String msg;
    Object data;
    public  static  Result success(String msg,Object data)
    {
        return new Result(200,msg,data);
    }
    public  static  Result error(String msg,Object data)
    {
        return new Result(-1,msg,data);
    }

}

創建全局異常處理器

注解里還嵌套了其他的注解

@RestControllAdvice = @ControllerAdvice + @ResponseBody

Exception捕獲了全局的異常,也就是說不管拋了什么異常,都可以捕獲到

@RestControllerAdvice //全局異常處理
public class AllException {

    @ExceptionHandler(Exception.class) //捕獲哪種類型的異常
    public Result ex(Exception ex){
        ex.printStackTrace(); //打印日常信息
        return  Result.error("發送了錯誤",null);
    }
}

在這里插入圖片描述

原文鏈接:https://blog.csdn.net/dpc5201314/article/details/136050241

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新