2023-08-25 10:24:29來源:Spring全家桶實(shí)戰(zhàn)案例源碼
當(dāng)程序發(fā)生異常時我們可以通過如下兩個注解來統(tǒng)一處理異常信息。
【資料圖】
他們的區(qū)別其實(shí)就是Rest的注解中多了一個@ResponseBody 注解(將方法的返回值,以特定的格式寫入到response的body,進(jìn)而將數(shù)據(jù)返回給客戶端,如果是字符串直接輸出字符串信息,如果是對象將會把對象轉(zhuǎn)為json進(jìn)行輸出)。
源碼:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @interface ControllerAdvice {}@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@ControllerAdvice@ResponseBodypublic @interface RestControllerAdvice {}
方式一、Controller內(nèi)部處理異常@RestControllerpublic class TestController { @GetMapping("/test/{id}") public Object test(@PathVariable Integer id) { if (id < 5) { throw new RuntimeException("運(yùn)行時異常") ; } return "測試異常處理" ; } @ExceptionHandler public Object handle(Exception e) { return e.getMessage() ; }}
這樣如果這個Controller中的接口發(fā)生了異常那么就會執(zhí)行有@ExceptionHandler標(biāo)注的方法。
該種方式處理異常只是針對當(dāng)前Controller,一個項目肯定會有很多的Controller,如果每一個類都這樣處理明顯是太麻煩,而且還不方便統(tǒng)一異常的處理。
方式二、全局異常處理可以在一個類上添加 @RestControllerAdvice或@ControlerAdvice
@RestControllerAdvicepublic class TestControllerAdvice { @ExceptionHandler public Object handle(Exception e) { return "我是全局異常:" + e.getMessage() ; } }
到此全局異常的使用方式就結(jié)束了當(dāng)你訪問接口時你會發(fā)現(xiàn)全局異常沒有起作用。
當(dāng)我們把controller中的@ExceptionHandler注釋了,這時全局異常才會生效。
結(jié)論:局部異常處理優(yōu)先級高于全局異常處理。
以上是項目中如果使用異常處理句柄的方式;接下來我們來看看在全局異常處理句柄中如何進(jìn)行局部控制(比如只處理有特定注解的或是只處理部分controller又或者是指定包下的controller)。
1、只處理特定注解自定義Annotation:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface AppAnnotation {}
Controller類:
有@AppAnnotation注解的Controller
@AppAnnotation@RestControllerpublic class AnnotationController { @GetMapping("/an/get/{id}") public Object an(@PathVariable Integer id) { if (id < 10) { throw new RuntimeException("發(fā)生錯誤了") ; } return "自定義Annotation注解: " + id ; } }
沒有@AppAnnotation注解的Controller
@RestControllerpublic class AnnotationController2 { @GetMapping("/an/get2/{id}") public Object an(@PathVariable Integer id) { if (id < 10) { throw new RuntimeException("2發(fā)生錯誤了") ; } return "自定義Annotation注解2: " + id ; }}
ControllerAdvice異常處理類:
@RestControllerAdvice(annotations = {AppAnnotation.class})public class AnnotationControllerAdvice { @ExceptionHandler public Object handle(Exception e) { return "特定注解全局異常:" + e.getMessage() ; } }
分別訪問/an/get/1 和/an/get2/1接口,只有有@AppAnnotation注解的Controller會被處理。
2、只處理指定的Controller新建UserController
@RestControllerpublic class UserController { @GetMapping("/user/{id}") public Object get(@PathVariable Integer id) { if (id < 10) { throw new RuntimeException("用戶ID錯誤") ; } return "Users" ; } }
新建PersonController
@RestControllerpublic class PersonController { @GetMapping("/person/{id}") public Object get(@PathVariable Integer id) { if (id < 10) { throw new RuntimeException("Person ID錯誤") ; } return "Person" ; } }
全局異常處理類:
@RestControllerAdvice(assignableTypes = {UserController.class})public class SpecificControllerAdvice { @ExceptionHandler public Object handle(Exception e) { return "指定Controller全局異常:" + e.getMessage() ; } }
這里通過assignableTypes屬性來限定了只有UserController類發(fā)生了異常才會做出響應(yīng)。
PersonController發(fā)生異常不會被處理。
3、指定包下的Controller
@RestControllerAdvice(basePackages = {"com.pack.pkg1"})public class PackageControllerAdvice { @ExceptionHandler public Object handle(Exception e) { return "指定包下的全局異常:" + e.getMessage() ; } }
UserController類位于pkg1包下:
package com.pack.pkg1;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;@RestController("userPController")public class UserController { @GetMapping("/userp/{id}") public Object get(@PathVariable Integer id) { if (id < 10) { throw new RuntimeException("用戶ID錯誤") ; } return "Users" ; }}
PersonController類位于pkg2包下:
package com.pack.pkg2;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;@RestController("personPController")public class PersonController { @GetMapping("/personp/{id}") public Object get(@PathVariable Integer id) { if (id < 10) { throw new RuntimeException("Person ID錯誤") ; } return "Person" ; }}
當(dāng)訪問com.pack.pkg1包下的接口出現(xiàn)異常后就會被處理。
到此結(jié)束關(guān)于@ExceptionHandler方法句柄可接受的參數(shù)及返回值大家可參考這里
接受的參數(shù)類型
圖片
關(guān)鍵詞:
當(dāng)程序發(fā)生異常時我們可以通過如下兩個注解來統(tǒng)一處理異常信息。@Contr
很多人的日常工作中,都會使用在線協(xié)作平臺或云存儲服務(wù)來存儲自己的各
在企業(yè)中,數(shù)據(jù)庫數(shù)據(jù)是非常重要的資產(chǎn),但數(shù)據(jù)丟失是一個巨大的挑戰(zhàn)。
充電樁顯示無線充電信息。新能源汽車正在進(jìn)行無線充電。安裝在車位上的
電動化浪潮席卷下,只有破局才能重生。時隔12年,東風(fēng)汽車集團(tuán)有限公司
在2023成都車展前夕,我們前方團(tuán)隊率先拍攝到一組奇瑞瑞虎7PLUS冠軍版
8月24日,安信穩(wěn)健匯利一年持有混合A最新單位凈值為1 0834元,累計凈值
浙江交科(002061 SZ)發(fā)布2023年半年度報告,公司營業(yè)收入182 81億元,
諸多的對于蹲便器堵塞怎么疏通生活小妙招,蹲便器堵塞怎么疏通這個問題
TechWeb】8月24日消息,今日,小鵬汽車CEO何小鵬今日曬出與原小鵬自動
新華社北京8月24日電記者從國家衛(wèi)生健康委了解到,國家衛(wèi)生健康委日前
隨著信息技術(shù)的快速發(fā)展,物聯(lián)網(wǎng)(InternetofThings,IoT)已經(jīng)逐漸走進(jìn)
隨著數(shù)字化時代的不斷演進(jìn),人們對于網(wǎng)絡(luò)連接的要求變得更加苛刻,特別
隨著網(wǎng)絡(luò)安全形勢的愈加嚴(yán)峻,如今企業(yè)也越來越重視網(wǎng)絡(luò)安全建設(shè),定期
前端開發(fā)框架是現(xiàn)代Web應(yīng)用開發(fā)的重要工具,它不僅可以幫助開發(fā)者構(gòu)建