在Java控制器中處理異常通常有以下幾種方式:
@GetMapping("/example")
public ResponseEntity<String> example() {
try {
// 業務邏輯代碼
return ResponseEntity.ok("Success");
} catch (Exception e) {
// 處理異常
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");
}
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");
}
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IOException.class)
public ResponseEntity<String> handleIOException(IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An IO error occurred");
}
@ExceptionHandler(SQLException.class)
public ResponseEntity<String> handleSQLException(SQLException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("A SQL error occurred");
}
}
通過以上方式,可以在Java控制器中靈活處理異常,提高系統的穩定性和可靠性。