日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

Spring MVC異常處理:這幾種方式讓你輕松應對,你都使用了那些方式?

來源: 責編: 時間:2023-10-06 19:21:28 340觀看
導讀環境:Spring5.3.231. 簡介Spring MVC提供了靈活的異常處理機制,可以讓開發者方便地處理應用程序中發生的各種異常。Spring MVC的異常處理主要依賴于Spring的@ControllerAdvice和@ExceptionHandler注解。@ControllerAdvi

環境:Spring5.3.23qwl28資訊網——每日最新資訊28at.com

1. 簡介

Spring MVC提供了靈活的異常處理機制,可以讓開發者方便地處理應用程序中發生的各種異常。Spring MVC的異常處理主要依賴于Spring的@ControllerAdvice和@ExceptionHandler注解。qwl28資訊網——每日最新資訊28at.com

@ControllerAdvice: 該注解用于定義一個全局的異常處理類,可以處理所有@RequestMapping方法中拋出的異常。例如,你可以創建一個全局的異常處理類,來處理所有的異常。qwl28資訊網——每日最新資訊28at.com

@ExceptionHandler: 該注解用于指定需要處理的異常類型。在全局異常處理類中,你可以使用@ExceptionHandler注解來指定需要處理的異常類型。例如,你可以創建一個全局的異常處理類,來處理所有的Exception異常。qwl28資訊網——每日最新資訊28at.com

現在基本上大部分項目都是前后端分離,API接口都是基于Restful。所以在項目中我們主要使用的是@RestControllerAdvice該注解與@ControllerAdvice主要區別其實就是Rest的注解中多了一個@ResponseBody 注解(將方法的返回值,以特定的格式寫入到response的body,進而將數據返回給客戶端,如果是字符串直接輸出字符串信息,如果是對象將會把對象轉為json進行輸出)。qwl28資訊網——每日最新資訊28at.com

部分源碼:qwl28資訊網——每日最新資訊28at.com

@Componentpublic @interface ControllerAdvice {}@ControllerAdvice@ResponseBodypublic @interface RestControllerAdvice {}

2. 應用案例

Controller內部處理異常

@RestControllerpublic class TestController {    @GetMapping("/test/{id}")  public Object test(@PathVariable Integer id) {    if (id < 5) {      throw new RuntimeException("運行時異常") ;    }    return "測試異常處理" ;  }  @ExceptionHandler  public Object handle(Exception e) {    return e.getMessage() ;  }}

這樣如果這個Controller中的接口發生了異常那么就會執行有@ExceptionHandler(當前還得根據異常進行匹配)標注的方法。qwl28資訊網——每日最新資訊28at.com

該種方式處理異常只是針對當前Controller,一個項目肯定會有很多的Controller,如果每一個類都這樣處理明顯是太麻煩,而且還不方便統一異常的處理。qwl28資訊網——每日最新資訊28at.com

全局異常處理

可以在一個類上添加 @RestControllerAdvice或@ControlerAdviceqwl28資訊網——每日最新資訊28at.com

@RestControllerAdvicepublic class TestControllerAdvice {  @ExceptionHandler  public Object handle(Exception e) {    return "我是全局異常:" + e.getMessage() ;  }  }

到此全局異常的使用方式就結束了當你訪問接口時你會發現全局異常沒有起作用。qwl28資訊網——每日最新資訊28at.com

當我們把controller中的@ExceptionHandler注釋了,這時全局異常才會生效。qwl28資訊網——每日最新資訊28at.com

結論:局部異常處理優先級高于全局異常處理。qwl28資訊網——每日最新資訊28at.com

以上是項目中如果使用異常處理句柄的方式;接下來我們來看看在全局異常處理句柄中如何進行局部控制(比如只處理有特定注解的或是只處理部分controller又或者是指定包下的controller)。qwl28資訊網——每日最新資訊28at.com

只處理特定注解

自定義Annotation:qwl28資訊網——每日最新資訊28at.com

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface AppAnnotation {}

Controller類:qwl28資訊網——每日最新資訊28at.com

有@AppAnnotation注解的Controller

@AppAnnotation@RestControllerpublic class AnnotationController {  @GetMapping("/an/get/{id}")  public Object an(@PathVariable Integer id) {    if (id < 10) {      throw new RuntimeException("發生錯誤了") ;    }    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發生錯誤了") ;    }    return "自定義Annotation注解2: " + id ;  }}

ControllerAdvice異常處理類:qwl28資訊網——每日最新資訊28at.com

@RestControllerAdvice(annotations = {AppAnnotation.class})public class AnnotationControllerAdvice {  @ExceptionHandler  public Object handle(Exception e) {    return "特定注解全局異常:" + e.getMessage() ;  }}

分別訪問/an/get/1 和/an/get2/1接口,只有有@AppAnnotation注解的Controller會被處理。qwl28資訊網——每日最新資訊28at.com

只處理指定的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" ;  }}

全局異常處理類:qwl28資訊網——每日最新資訊28at.com

@RestControllerAdvice(assignableTypes = {UserController.class})public class SpecificControllerAdvice {  @ExceptionHandler  public Object handle(Exception e) {    return "指定Controller全局異常:" + e.getMessage() ;  }}

這里通過assignableTypes屬性來限定了只有UserController類發生了異常才會做出響應。qwl28資訊網——每日最新資訊28at.com

PersonController發生異常不會被處理。qwl28資訊網——每日最新資訊28at.com

指定包下的Controller

@RestControllerAdvice(basePackages = {"com.pack.pkg1"})public class PackageControllerAdvice {    @ExceptionHandler  public Object handle(Exception e) {    return "指定包下的全局異常:" + e.getMessage() ;  }  }

UserController類位于pkg1包下:qwl28資訊網——每日最新資訊28at.com

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包下:qwl28資訊網——每日最新資訊28at.com

package com.pack.pkg2;@RestController("personPController")public class PersonController {  @GetMapping("/personp/{id}")  public Object get(@PathVariable Integer id) {    if (id < 10) {      throw new RuntimeException("Person ID錯誤") ;    }    return "Person" ;  }}

當訪問com.pack.pkg1包下的接口出現異常后就會被處理。qwl28資訊網——每日最新資訊28at.com

完畢!!!qwl28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-12169-0.htmlSpring MVC異常處理:這幾種方式讓你輕松應對,你都使用了那些方式?

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 國慶將至,你的“國旗頭像”、“國慶頭像”、“愛國頭像”都做好了嗎?

下一篇: 九款開源、免費、實用、美觀的Blazor UI框架

標簽:
  • 熱門焦點
  • K60 Pro官方停產 第三方瞬間漲價

    雖然沒有官方宣布,但Redmi的一些高管也已經透露了,Redmi K60 Pro已經停產且不會補貨,這一切都是為了即將到來的K60 Ultra鋪路,屬于廠家的正常操作。但有意思的是該機在停產之后
  • iPhone賣不動了!蘋果股價創年內最大日跌幅:市值一夜蒸發萬億元

    8月5日消息,今天凌晨美股三大指數高開低走集體收跌,道指跌0.41%;納指跌0.36%;標普500指數跌0.52%。熱門科技股也都變化極大,其中蘋果報181.99美元,跌4.8%,創
  • 十個簡單但很有用的Python裝飾器

    裝飾器(Decorators)是Python中一種強大而靈活的功能,用于修改或增強函數或類的行為。裝飾器本質上是一個函數,它接受另一個函數或類作為參數,并返回一個新的函數或類。它們通常用
  • JavaScript學習 -AES加密算法

    引言在當今數字化時代,前端應用程序扮演著重要角色,用戶的敏感數據經常在前端進行加密和解密操作。然而,這樣的操作在網絡傳輸和存儲中可能會受到惡意攻擊的威脅。為了確保數據
  • 慕巖炮轟抖音,百合網今何在?

    來源:價值研究所 作者:Hernanderz&ldquo;難道就因為自己的一個產品牛逼了,從客服到總裁,都不愿意正視自己產品和運營上的問題,選擇逃避了嗎?&rdquo;這一番話,出自百合網聯合創
  • 梁柱接棒兩年,騰訊音樂闖出新路子

    文丨田靜 出品丨牛刀財經(niudaocaijing)7月5日,企鵝FM發布官方公告稱由于業務調整,將于9月6日正式停止運營,這意味著騰訊音樂長音頻業務走向消亡。騰訊在長音頻領域還在摸索。為
  • 攜眾多高端產品亮相ChinaJoy,小米帶來一場科技與人文的視聽盛宴

    7月28日,全球數字娛樂領域最具知名度與影響力的年度盛會中國國際數碼互動娛樂展覽會(簡稱ChinaJoy)在上海新國際博覽中心盛大開幕。作為全球領先的科
  • 滴滴違法違規被罰80.26億 共存在16項違法事實

    滴滴違法違規被罰80.26億 存在16項違法事實開始于2121年7月,歷經一年時間,網絡安全審查辦公室對“滴滴出行”網絡安全審查終于有了一個暫時的結束。據“網信
  • 電博會上海爾智家模擬500平大平層,還原生活空間沉浸式體驗

    電博會為了更好地讓參展觀眾真正感受到智能家居的絕妙之處,海爾智家的程傳嶺先生同樣介紹了展會上海爾智家的模擬500平大平層,還原生活空間沉浸式體驗。程傳
Top 主站蜘蛛池模板: 六盘水市| 兴海县| 乌苏市| 永善县| 巫溪县| 宣汉县| 同江市| 高平市| 博湖县| 西昌市| 拜城县| 临西县| 南通市| 襄垣县| 文水县| 墨玉县| 昭平县| 曲水县| 巨野县| 东丰县| 申扎县| 和田市| 怀集县| 正安县| 芦溪县| 博乐市| 乐至县| 壤塘县| 博客| 威海市| 弋阳县| 介休市| 白河县| 浦江县| 宁武县| 六安市| 崇左市| 德安县| 渭源县| 克东县| 瓮安县|