自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

SpringBoot 處理異常的幾種常見姿勢(shì)

新聞 前端
這是目前很常用的一種方式,非常推薦。測(cè)試代碼中用到了 Junit 5,如果你新建項(xiàng)目驗(yàn)證下面的代碼的話,記得添加上相關(guān)依賴。

一、使用 @ControllerAdvice 和 @ExceptionHandler 處理全局異常

這是目前很常用的一種方式,非常推薦。測(cè)試代碼中用到了 Junit 5,如果你新建項(xiàng)目驗(yàn)證下面的代碼的話,記得添加上相關(guān)依賴。

1. 新建異常信息實(shí)體類

非必要的類,主要用于包裝異常信息。

src/main/java/com/twuc/webApp/exception/ErrorResponse.java

  1. /** 
  2.  * @author shuang.kou 
  3.  */ 
  4. public class ErrorResponse { 
  5.  private String message; 
  6.  private String errorTypeName; 
  7.  public ErrorResponse(Exception e) { 
  8.  this(e.getClass().getName(), e.getMessage()); 
  9.  } 
  10.  public ErrorResponse(String errorTypeName, String message) { 
  11.  this.errorTypeName = errorTypeName; 
  12.  this.message = message; 
  13.  } 
  14.  ......省略getter/setter方法 

2. 自定義異常類型

src/main/java/com/twuc/webApp/exception/ResourceNotFoundException.java

一般我們處理的都是 RuntimeException ,所以如果你需要自定義異常類型的話直接集成這個(gè)類就可以了。

  1. /** 
  2.  * @author shuang.kou 
  3.  * 自定義異常類型 
  4.  */ 
  5. public class ResourceNotFoundException extends RuntimeException { 
  6.  private String message; 
  7.  public ResourceNotFoundException() { 
  8.  super(); 
  9.  } 
  10.  public ResourceNotFoundException(String message) { 
  11.  super(message); 
  12.  this.message = message; 
  13.  } 
  14.  @Override 
  15.  public String getMessage() { 
  16.  return message; 
  17.  } 
  18.  public void setMessage(String message) { 
  19.  this.message = message; 
  20.  } 

3. 新建異常處理類

我們只需要在類上加上@ControllerAdvice注解這個(gè)類就成為了全局異常處理類,當(dāng)然你也可以通過 assignableTypes指定特定的 Controller 類,讓異常處理類只處理特定類拋出的異常。

src/main/java/com/twuc/webApp/exception/GlobalExceptionHandler.java

  1. /** 
  2.  * @author shuang.kou 
  3.  */ 
  4. @ControllerAdvice(assignableTypes = {ExceptionController.class}) 
  5. @ResponseBody 
  6. public class GlobalExceptionHandler { 
  7.  ErrorResponse illegalArgumentResponse = new ErrorResponse(new IllegalArgumentException("參數(shù)錯(cuò)誤!")); 
  8.  ErrorResponse resourseNotFoundResponse = new ErrorResponse(new ResourceNotFoundException("Sorry, the resourse not found!")); 
  9.  @ExceptionHandler(value = Exception.class)// 攔截所有異常, 這里只是為了演示,一般情況下一個(gè)方法特定處理一種異常 
  10.  public ResponseEntity<ErrorResponse> exceptionHandler(Exception e) { 
  11.  if (e instanceof IllegalArgumentException) { 
  12.  return ResponseEntity.status(400).body(illegalArgumentResponse); 
  13.  } else if (e instanceof ResourceNotFoundException) { 
  14.  return ResponseEntity.status(404).body(resourseNotFoundResponse); 
  15.  } 
  16.  return null
  17.  } 

4. controller模擬拋出異常

src/main/java/com/twuc/webApp/web/ExceptionController.java

  1. /** 
  2.  * @author shuang.kou 
  3.  */ 
  4. @RestController 
  5. @RequestMapping("/api"
  6. public class ExceptionController { 
  7.  @GetMapping("/illegalArgumentException"
  8.  public void throwException() { 
  9.  throw new IllegalArgumentException(); 
  10.  } 
  11.  @GetMapping("/resourceNotFoundException"
  12.  public void throwException2() { 
  13.  throw new ResourceNotFoundException(); 
  14.  } 

使用 Get 請(qǐng)求 localhost:8080/api/resourceNotFoundException[1] (curl -i -s -X GET url),服務(wù)端返回的 JSON 數(shù)據(jù)如下:

  1.  "message""Sorry, the resourse not found!"
  2.  "errorTypeName""com.twuc.webApp.exception.ResourceNotFoundException" 

5. 編寫測(cè)試類

MockMvc 由org.springframework.boot.test包提供,實(shí)現(xiàn)了對(duì)Http請(qǐng)求的模擬,一般用于我們測(cè)試 controller 層。

  1. /** 
  2.  * @author shuang.kou 
  3.  */ 
  4. @AutoConfigureMockMvc 
  5. @SpringBootTest 
  6. public class ExceptionTest { 
  7.  @Autowired 
  8.  MockMvc mockMvc; 
  9.  @Test 
  10.  void should_return_400_if_param_not_valid() throws Exception { 
  11.  mockMvc.perform(get("/api/illegalArgumentException")) 
  12.  .andExpect(status().is(400)) 
  13.  .andExpect(jsonPath("$.message").value("參數(shù)錯(cuò)誤!")); 
  14.  } 
  15.  @Test 
  16.  void should_return_404_if_resourse_not_found() throws Exception { 
  17.  mockMvc.perform(get("/api/resourceNotFoundException")) 
  18.  .andExpect(status().is(404)) 
  19.  .andExpect(jsonPath("$.message").value("Sorry, the resourse not found!")); 
  20.  } 

二、 @ExceptionHandler 處理 Controller 級(jí)別的異常

我們剛剛也說了使用@ControllerAdvice注解 可以通過 assignableTypes指定特定的類,讓異常處理類只處理特定類拋出的異常。所以這種處理異常的方式,實(shí)際上現(xiàn)在使用的比較少了。

我們把下面這段代碼移到 src/main/java/com/twuc/webApp/exception/GlobalExceptionHandler.java 中就可以了。

  1. @ExceptionHandler(value = Exception.class)// 攔截所有異常 
  2. public ResponseEntity<ErrorResponse> exceptionHandler(Exception e) { 
  3. if (e instanceof IllegalArgumentException) { 
  4. return ResponseEntity.status(400).body(illegalArgumentResponse); 
  5. else if (e instanceof ResourceNotFoundException) { 
  6. return ResponseEntity.status(404).body(resourseNotFoundResponse); 
  7. return null

三、 ResponseStatusException

研究 ResponseStatusException 我們先來看看,通過 ResponseStatus注解簡(jiǎn)單處理異常的方法(將異常映射為狀態(tài)碼)。

src/main/java/com/twuc/webApp/exception/ResourceNotFoundException.java

  1. @ResponseStatus(code = HttpStatus.NOT_FOUND) 
  2. public class ResourseNotFoundException2 extends RuntimeException { 
  3.  public ResourseNotFoundException2() { 
  4.  } 
  5.  public ResourseNotFoundException2(String message) { 
  6.  super(message); 
  7.  } 

src/main/java/com/twuc/webApp/web/ResponseStatusExceptionController.java

  1. @RestController 
  2. @RequestMapping("/api"
  3. public class ResponseStatusExceptionController { 
  4.  @GetMapping("/resourceNotFoundException2"
  5.  public void throwException3() { 
  6.  throw new ResourseNotFoundException2("Sorry, the resourse not found!"); 
  7.  } 

使用 Get 請(qǐng)求 localhost:8080/api/resourceNotFoundException2[2] ,服務(wù)端返回的 JSON 數(shù)據(jù)如下:

  1.  "timestamp""2019-08-21T07:11:43.744+0000"
  2.  "status"404
  3.  "error""Not Found"
  4.  "message""Sorry, the resourse not found!"
  5.  "path""/api/resourceNotFoundException2" 

這種通過 ResponseStatus注解簡(jiǎn)單處理異常的方法是的好處是比較簡(jiǎn)單,但是一般我們不會(huì)這樣做,通過ResponseStatusException會(huì)更加方便,可以避免我們額外的異常類。

  1. @GetMapping("/resourceNotFoundException2"
  2. public void throwException3() { 
  3. throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Sorry, the resourse not found!"new ResourceNotFoundException()); 

使用 Get 請(qǐng)求 localhost:8080/api/resourceNotFoundException2[3] ,服務(wù)端返回的 JSON 數(shù)據(jù)如下,和使用 ResponseStatus 實(shí)現(xiàn)的效果一樣:

  1.  "timestamp""2019-08-21T07:28:12.017+0000"
  2.  "status"404
  3.  "error""Not Found"
  4.  "message""Sorry, the resourse not found!"
  5.  "path""/api/resourceNotFoundException3" 

ResponseStatusException 提供了三個(gè)構(gòu)造方法:

  1. public ResponseStatusException(HttpStatus status) { 
  2.  this(status, nullnull); 
  3.  } 
  4.  public ResponseStatusException(HttpStatus status, @Nullable String reason) { 
  5.  this(status, reason, null); 
  6.  } 
  7.  public ResponseStatusException(HttpStatus status, @Nullable String reason, @Nullable Throwable cause) { 
  8.  super(null, cause); 
  9.  Assert.notNull(status, "HttpStatus is required"); 
  10.  this.status = status; 
  11.  this.reason = reason; 
  12.  } 

構(gòu)造函數(shù)中的參數(shù)解釋如下:

•status :http status

•reason :response 的消息內(nèi)容

•cause :拋出的異常

 

責(zé)任編輯:張燕妮 來源: 今日頭條
相關(guān)推薦

2024-08-02 09:15:22

Spring捕捉格式

2024-10-18 08:53:49

SpringMybatis微服務(wù)

2024-08-28 08:45:22

2009-11-05 12:45:25

WCF異常

2020-04-13 15:25:01

MySQL數(shù)據(jù)庫模糊搜索

2022-03-04 08:31:07

Spring異常處理

2019-01-24 16:11:19

前端全局異常數(shù)據(jù)校驗(yàn)

2017-08-10 10:28:43

SpringBootSpring

2017-12-11 14:12:40

PythonMySQL連接

2021-03-10 10:05:59

網(wǎng)絡(luò)釣魚攻擊黑客

2021-01-13 08:14:36

Windows提權(quán)漏洞攻擊

2017-05-05 11:31:34

2023-01-30 07:41:43

2019-09-03 15:26:52

Linuxawk文字?jǐn)?shù)據(jù)

2010-08-17 15:31:54

DB2 存儲(chǔ)過程

2009-12-03 10:49:32

PHP自定義異常處理器

2009-08-06 15:35:34

C# Web Serv

2024-10-07 08:26:05

編程Python異常處理

2019-11-15 14:14:13

Python開發(fā)BaseExcepti

2011-09-15 09:34:48

ubuntu輸入法
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)