溫馨提示×

Springboot統一異常處理的方法是什么

小億
132
2023-08-09 10:12:32
欄目: 編程語言

Spring Boot提供了一個全局異常處理的方法,可以通過編寫一個@ControllerAdvice注解的類來實現統一異常處理。

具體步驟如下:

  1. 創建一個類并使用@ControllerAdvice注解標注,該類需要被Spring掃描到。

  2. 在該類中編寫異常處理方法,可以使用@ExceptionHandler注解來標注處理特定異常的方法。

  3. 在處理方法中,可以根據需要對異常進行處理,比如記錄日志、返回特定的錯誤信息等。

  4. 可以使用@ResponseStatus注解來標注處理方法的返回狀態碼。

示例代碼如下:

@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<String> handleException(Exception e) {
// 處理異常的邏輯,比如記錄日志、返回錯誤信息等
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error");
}
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntity<String> handleNotFoundException(NotFoundException e) {
// 處理特定異常的邏輯
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Not Found");
}
}

在上面的代碼中,handleException方法使用@ExceptionHandler注解標注,該方法會處理所有未被其他處理方法處理的異常,并返回500狀態碼和錯誤信息"Internal Server Error"。

handleNotFoundException方法處理NotFoundException異常,并返回404狀態碼和錯誤信息"Not Found"。

注意,需要根據具體需求來編寫異常處理方法,并可以根據業務需要定義自己的異常類。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女