在SpringBoot中處理異常可以通過編寫一個全局異常處理器來實現。一般情況下,我們可以繼承Spring的ResponseEntityExceptionHandler類,并重寫handleException方法來處理異常。具體實現步驟如下:
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
// 處理所有異常
ErrorResponse errorResponse = new ErrorResponse("500", ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<Object> handleNotFoundException(NotFoundException ex, WebRequest request) {
// 處理自定義異常
ErrorResponse errorResponse = new ErrorResponse("404", ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
}
}
public class NotFoundException extends RuntimeException {
public NotFoundException(String message) {
super(message);
}
}
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
throw new NotFoundException("Resource not found");
}
}
通過以上步驟,我們就可以在SpringBoot項目中統一處理異常,并返回統一的錯誤信息給客戶端。在GlobalExceptionHandler中,我們可以定義不同的異常處理方法來處理不同類型的異常,以實現更細粒度的異常處理。