Spring MVC異常處理:這幾種方式讓你輕松應對,你都使用了那些方式?
環(huán)境:Spring5.3.23
1. 簡介
Spring MVC提供了靈活的異常處理機制,可以讓開發(fā)者方便地處理應用程序中發(fā)生的各種異常。Spring MVC的異常處理主要依賴于Spring的@ControllerAdvice和@ExceptionHandler注解。
@ControllerAdvice: 該注解用于定義一個全局的異常處理類,可以處理所有@RequestMapping方法中拋出的異常。例如,你可以創(chuàng)建一個全局的異常處理類,來處理所有的異常。
@ExceptionHandler: 該注解用于指定需要處理的異常類型。在全局異常處理類中,你可以使用@ExceptionHandler注解來指定需要處理的異常類型。例如,你可以創(chuàng)建一個全局的異常處理類,來處理所有的Exception異常。
現(xiàn)在基本上大部分項目都是前后端分離,API接口都是基于Restful。所以在項目中我們主要使用的是@RestControllerAdvice該注解與@ControllerAdvice主要區(qū)別其實就是Rest的注解中多了一個@ResponseBody 注解(將方法的返回值,以特定的格式寫入到response的body,進而將數(shù)據(jù)返回給客戶端,如果是字符串直接輸出字符串信息,如果是對象將會把對象轉為json進行輸出)。
部分源碼:
@Component
public @interface ControllerAdvice {
}
@ControllerAdvice
@ResponseBody
public @interface RestControllerAdvice {
}
2. 應用案例
Controller內部處理異常
@RestController
public 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中的接口發(fā)生了異常那么就會執(zhí)行有@ExceptionHandler(當前還得根據(jù)異常進行匹配)標注的方法。
該種方式處理異常只是針對當前Controller,一個項目肯定會有很多的Controller,如果每一個類都這樣處理明顯是太麻煩,而且還不方便統(tǒng)一異常的處理。
全局異常處理
可以在一個類上添加 @RestControllerAdvice或@ControlerAdvice
@RestControllerAdvice
public class TestControllerAdvice {
@ExceptionHandler
public Object handle(Exception e) {
return "我是全局異常:" + e.getMessage() ;
}
}
到此全局異常的使用方式就結束了當你訪問接口時你會發(fā)現(xiàn)全局異常沒有起作用。
當我們把controller中的@ExceptionHandler注釋了,這時全局異常才會生效。
結論:局部異常處理優(yōu)先級高于全局異常處理。
以上是項目中如果使用異常處理句柄的方式;接下來我們來看看在全局異常處理句柄中如何進行局部控制(比如只處理有特定注解的或是只處理部分controller又或者是指定包下的controller)。
只處理特定注解
自定義Annotation:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AppAnnotation {
}
Controller類:
有@AppAnnotation注解的Controller
@AppAnnotation
@RestController
public class AnnotationController {
@GetMapping("/an/get/{id}")
public Object an(@PathVariable Integer id) {
if (id < 10) {
throw new RuntimeException("發(fā)生錯誤了") ;
}
return "自定義Annotation注解: " + id ;
}
}
沒有@AppAnnotation注解的Controller
@RestController
public 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會被處理。
只處理指定的Controller
新建UserController
@RestController
public class UserController {
@GetMapping("/user/{id}")
public Object get(@PathVariable Integer id) {
if (id < 10) {
throw new RuntimeException("用戶ID錯誤") ;
}
return "Users" ;
}
}
新建PersonController
@RestController
public 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ā)生了異常才會做出響應。
PersonController發(fā)生異常不會被處理。
指定包下的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;
@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包下的接口出現(xiàn)異常后就會被處理。
完畢?。?!