REST介面定義全域性異常碼以及異常資訊

2021-09-20 06:37:24 字數 2259 閱讀 7892

在編寫rest介面時,常常會丟擲各種各樣的異常,比如系統錯誤,請求引數不合法,沒有許可權,token檢驗未通過等等,這時如果直接丟擲異常,不僅對使用者不友好,而且會暴露程式內部資訊,這種做法是不可取的,程式可以對異常進行攔截,並進一步封裝。同時,對於程式異常,如果有一整套異常碼以及對應的異常資訊,那麼也非常便於排查異常。下面就來介紹一下基於***實現全域性異常攔截。

一、定義介面返回包裝類baseresponse

@data

@allargsconstructor

@noargsconstructor

public class baseresponseimplements serializable

public baseresponse(int code, string message)

}

二、定義全域性異常類bizexception

@data

@equalsandhashcode(callsuper = true)

public class bizexception extends runtimeexception

public bizexception(integer code, string message, throwable cause)

}

、定義全域性異常碼以及異常資訊(異常碼與異常資訊視業務而定,這裡只列舉幾個做示例)

public enum systemevent 

public integer getid()

public string getdetails()

}

、定義全域性異常***

@responsebody

@controlleradvice(basepackages = "com.shuwei.userprofile.web.controller")

public class exceptioninterceptor extends responseentityexceptionhandler

/*** json格式錯誤異常.

/*** 業務主動失敗異常. 所有丟擲bizexception都會被攔截.

}

這樣就實現了全域性異常攔截,所有丟擲的異常都會被這個***攔截並進一步封裝轉化為異常碼和異常資訊,如下圖:

35 定義介面以及繼承介面

定義介面以及繼承介面 介面的實現,稱為契約繼承,它僅約定繼承的行為名稱,並不約束繼承行為 一般類的繼承是繼承父類的行為 1.前置inte ce定義介面 介面不能像類一樣用於建立新物件 inte ce myitf1 3.前置inte ce定義介面 inte ce myitf2 5.定義類a,同時用im...

Spring 全域性異常捕獲 自定義業務異常

響應前端成功效果 code 200 失敗效果 responseresult 統一向前端返回結果集 package com.cs.demo.exception author chan date 2020 01 18 public class responseresult public response...

SpringBoot自定義異常全域性捕獲

前言 不會寫bug的程式設計師不是乙個好程式設計師,不出異常的程式不是好程式,我們要做的就是抓住它,然後接著寫bug 建立自定義異常類 基礎異常 public class baseexception extends runtimeexception public baseexception stri...