溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot中處理異常的方法有哪些

發(fā)布時(shí)間:2021-06-11 15:53:16 來源:億速云 閱讀:159 作者:Leah 欄目:編程語言

SpringBoot中處理異常的方法有哪些,相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

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

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

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

/** 
 * @author shuang.kou 
 */ 
public class ErrorResponse { 
 private String message; 
 private String errorTypeName; 
 public ErrorResponse(Exception e) { 
 this(e.getClass().getName(), e.getMessage()); 
 } 
 public ErrorResponse(String errorTypeName, String message) { 
 this.errorTypeName = errorTypeName; 
 this.message = message; 
 } 
 ......省略getter/setter方法 
}

2. 自定義異常類型

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

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

/** 
 * @author shuang.kou 
 * 自定義異常類型 
 */ 
public class ResourceNotFoundException extends RuntimeException { 
 private String message; 
 public ResourceNotFoundException() { 
 super(); 
 } 
 public ResourceNotFoundException(String message) { 
 super(message); 
 this.message = message; 
 } 
 @Override 
 public String getMessage() { 
 return message; 
 } 
 public void setMessage(String message) { 
 this.message = message; 
 } 
}

3. 新建異常處理類

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

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

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

4. controller模擬拋出異常

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

/** 
 * @author shuang.kou 
 */ 
@RestController 
@RequestMapping("/api") 
public class ExceptionController { 
 @GetMapping("/illegalArgumentException") 
 public void throwException() { 
 throw new IllegalArgumentException(); 
 } 
 @GetMapping("/resourceNotFoundException") 
 public void throwException2() { 
 throw new ResourceNotFoundException(); 
 } 
}

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

{ 
 "message": "Sorry, the resourse not found!", 
 "errorTypeName": "com.twuc.webApp.exception.ResourceNotFoundException" 
}

5. 編寫測試類

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

/** 
 * @author shuang.kou 
 */ 
@AutoConfigureMockMvc 
@SpringBootTest 
public class ExceptionTest { 
 @Autowired 
 MockMvc mockMvc; 
 @Test 
 void should_return_400_if_param_not_valid() throws Exception { 
 mockMvc.perform(get("/api/illegalArgumentException")) 
 .andExpect(status().is(400)) 
 .andExpect(jsonPath("$.message").value("參數(shù)錯(cuò)誤!")); 
 } 
 @Test 
 void should_return_404_if_resourse_not_found() throws Exception { 
 mockMvc.perform(get("/api/resourceNotFoundException")) 
 .andExpect(status().is(404)) 
 .andExpect(jsonPath("$.message").value("Sorry, the resourse not found!")); 
 } 
}

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

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

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

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

三、 ResponseStatusException

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

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

@ResponseStatus(code = HttpStatus.NOT_FOUND) 
public class ResourseNotFoundException2 extends RuntimeException { 
 public ResourseNotFoundException2() { 
 } 
 public ResourseNotFoundException2(String message) { 
 super(message); 
 } 
}

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

@RestController 
@RequestMapping("/api") 
public class ResponseStatusExceptionController { 
 @GetMapping("/resourceNotFoundException2") 
 public void throwException3() { 
 throw new ResourseNotFoundException2("Sorry, the resourse not found!"); 
 } 
}

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

{ 
 "timestamp": "2019-08-21T07:11:43.744+0000", 
 "status": 404, 
 "error": "Not Found", 
 "message": "Sorry, the resourse not found!", 
 "path": "/api/resourceNotFoundException2" 
}

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

@GetMapping("/resourceNotFoundException2") 
public void throwException3() { 
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)的效果一樣:

{ 
 "timestamp": "2019-08-21T07:28:12.017+0000", 
 "status": 404, 
 "error": "Not Found", 
 "message": "Sorry, the resourse not found!", 
 "path": "/api/resourceNotFoundException3" 
}

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

public ResponseStatusException(HttpStatus status) { 
 this(status, null, null); 
 } 
 public ResponseStatusException(HttpStatus status, @Nullable String reason) { 
 this(status, reason, null); 
 } 
 public ResponseStatusException(HttpStatus status, @Nullable String reason, @Nullable Throwable cause) { 
 super(null, cause); 
 Assert.notNull(status, "HttpStatus is required"); 
 this.status = status; 
 this.reason = reason; 
 }

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

  • status :http status

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

  • cause :拋出的異常

看完上述內(nèi)容,你們掌握SpringBoot中處理異常的方法有哪些的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI