技能 error-handling-patterns
📦

error-handling-patterns

安全

實作穩健的錯誤處理模式

應用程式常因錯誤處理不佳而意外失敗。本技能提供經過實際驗證的異常處理、Result 類型、熔斷器和優雅降級模式,適用於 Python、TypeScript、Rust 和 Go。

支援: Claude Codex Code(CC)
🥉 72 青銅
1

下載技能 ZIP

2

在 Claude 中上傳

前往 設定 → 功能 → 技能 → 上傳技能

3

開啟並開始使用

測試它

正在使用「error-handling-patterns」。 Add error handling to a function that reads a file and parses JSON content.

預期結果:

Here is a pattern for robust file handling with proper error hierarchy:

**Python Example:**
```python
class FileReadError(ApplicationError):
"""Raised when file read operations fail."""
pass

class ParseError(ApplicationError):
"""Raised when JSON parsing fails."""
pass

def read_json_file(path: str) -> dict:
try:
with open(path, 'r') as f:
content = f.read()
return json.loads(content)
except FileNotFoundError as e:
raise FileReadError(f"File not found: {path}", details={"path": path}) from e
except json.JSONDecodeError as e:
raise ParseError(f"Invalid JSON in file: {path}", details={"path": path, "error": str(e)}) from e
```

**Key practices:**
- Use specific exception types for different error scenarios
- Include contextual information in exceptions
- Chain exceptions to preserve original stack trace
- Use context managers for automatic resource cleanup

正在使用「error-handling-patterns」。 How should I handle errors in an async function that calls multiple services in parallel?

預期結果:

For parallel service calls, consider these strategies:

**Option 1: Aggregate Errors**
Collect all errors and report them together rather than failing on the first error.

```typescript
async function fetchUserData(userId: string): Promise<UserData> {
const errors: Error[] = [];
let user: User | null = null;
let orders: Order[] = [];

try { user = await userService.getUser(userId); }
catch (e) { errors.push(e); }

try { orders = await orderService.getOrders(userId); }
catch (e) { errors.push(e); }

if (errors.length > 0) {
throw new AggregateError(errors, `${errors.length} operations failed`);
}

return { user, orders };
}
```

**Option 2: Result Types**
Use explicit success/failure types for each operation.

```typescript
async function fetchUserData(userId: string): Promise<Result<UserData>> {
const [userResult, ordersResult] = await Promise.all([
safePromise(userService.getUser(userId)),
safePromise(orderService.getOrders(userId))
]);

if (!userResult.ok) return Err(userResult.error);
if (!ordersResult.ok) return Err(ordersResult.error);

return Ok({ user: userResult.value, orders: ordersResult.value });
}
```

正在使用「error-handling-patterns」。 What are the worst error handling anti-patterns to avoid?

預期結果:

Here are the most dangerous anti-patterns and their fixes:

**Anti-Pattern 1: Empty Catch Blocks**
```python
try:
do_something()
except:
pass # Silent failure - bugs hide forever
```
**Fix:** Always log or re-raise exceptions.

**Anti-Pattern 2: Catching Too Broadly**
```python
try:
do_something()
except Exception:
# Hides bugs including typos and logic errors
pass
```
**Fix:** Catch specific exception types only.

**Anti-Pattern 3: Swallowing After Logging**
```python
try:
do_something()
except Exception as e:
logger.error(e)
# Error logged but not handled - caller doesn't know it failed
```
**Fix:** Re-raise or return error result.

**Anti-Pattern 4: Overly Generic Errors**
```python
raise Exception("Error occurred") # No context, no code, useless for debugging
```
**Fix:** Include what happened, what was being processed, and error codes.

安全審計

安全
v5 • 1/21/2026

All static findings are false positives. The skill is legitimate educational documentation about error handling patterns across Python, TypeScript, Rust, and Go. Static scanner misidentified 'error' keywords as cryptographic issues and Markdown code fences as shell backticks. No actual network calls, command execution, or malicious patterns exist in the skill content.

2
已掃描檔案
1,236
分析行數
0
發現項
5
審計總數
未發現安全問題
審計者: claude 查看審計歷史 →

品質評分

38
架構
100
可維護性
87
內容
41
社群
100
安全
87
規範符合性

你能建構什麼

建置生產級 API 錯誤處理

為新的 REST API 設計錯誤處理,返回一致的錯誤響應,包含適當的 HTTP 狀態碼、錯誤代碼以及對 API 使用者有幫助的訊息。

為分散式系統新增彈性

實作熔斷器和重試模式,防止外部服務不可用時發生連鎖故障,確保系統能優雅降級。

改善程式碼審查中關於錯誤處理的反饋

對拉取請求中的錯誤處理提供具體、可操作的反饋,識別反模式,如空catch區塊或過於廣泛的異常處理。

試試這些提示

基本錯誤處理實作
我需要為一個呼叫外部 API 的 {language} 函式進行錯誤處理。該函式應在網路故障時重試並具有指數退避,包含適當的錯誤類型,並提供清晰的錯誤訊息以便偵錯。
自訂異常層級設計
為 {application_type} 應用程式設計自訂異常層級結構。包括基礎異常類別、針對驗證、找不到和外部服務故障的特定錯誤類型。每個異常應包含錯誤代碼、時間戳記和相關上下文。
熔斷器整合
為呼叫不可靠的第三方 API 的服務實作熔斷器模式。包含故障閾值、超時持續時間和用於恢復測試的半開狀態的配置。
多錯誤驗證聚合
建立一個收集所有驗證錯誤而非在第一個錯誤時失敗的驗證系統。展示如何從多個欄位聚合錯誤並將其作為結構化響應返回。

最佳實務

  • 建立具有上下文資訊的特定異常類型,包括錯誤代碼、時間戳記和用於偵錯的相關元數據
  • 對預期失敗使用 Result 類型或明確的錯誤返回,使錯誤處理在可能的情況下在編譯時強制執行並可見
  • 為外部相依性實作熔斷器,以防止連鎖故障並允許優雅降級
  • 以適當的嚴重程度記錄錯誤 - 實際問題使用錯誤級別,預期失敗使用警告,永遠不用於正常流程

避免

  • 空catch區塊會默默吞掉錯誤,隱藏錯誤並使偵錯變得不可能
  • 過度廣泛的異常處理程式(如 `except Exception`)會掩蓋程式錯誤以及預期失敗
  • 記錄異常而不重新引發它們,會產生重複的日誌項目和混亂的控制流程
  • 返回通用的錯誤代碼而非類型化異常,使錯誤處理冗長且容易出錯

常見問題

什麼時候應該使用異常而非 Result 類型?
對意外的、異常的情況(如網路故障、檔案找不到或程式錯誤)使用異常。對預期失敗(如驗證錯誤、速率限制或業務規則違規)使用 Result 類型。異常會中斷控制流,而 Result 類型使錯誤處理明確且強制執行。
如何設計一個好的錯誤層級結構?
從一個捕獲常見欄位(如時間戳記、錯誤代碼和上下文)的基礎 ApplicationError 開始。為每個錯誤域建立特定的子類別:ValidationError、NotFoundError、ExternalServiceError、AuthenticationError。避免深層繼承層級結構 - 通常 2-3 層就足夠了。
什麼是熔斷器,什麼時候應該使用它?
熔斷器透過停止向故障服務發出請求來防止連鎖故障。它有三種狀態:關閉(正常操作)、開啟(請求快速失敗)和半開(測試恢復)。對任何外部服務呼叫使用它,在那裡重複故障可能耗盡資源或影響使用者體驗。
如何在非同步代碼中處理錯誤?
在 async/await 代碼中,在 await 語句周圍使用 try/catch。在 Promise 鏈中,始終添加 .catch() 處理程式。小心未處理的 promise 拒絕 - 它們可能導致 Node.js 程序崩潰。考慮對 async 操作使用 Result 類型以使故障明確。
錯誤訊息中應該包含什麼資訊?
包含嘗試執行的操作、輸入或資源是什麼、為什麼失敗,以及使用者或開發人員可以怎麼做。避免暴露敏感資料。對於程式化處理,使用帶有錯誤代碼的結構化格式。
如何有效地測試錯誤處理?
使用模擬來觸發特定故障,明確測試每條錯誤路徑。驗證錯誤包含預期的上下文和代碼。透過模擬暫時性故障來測試重試邏輯。確保熔斷器在故障條件下正確地在狀態之間轉換。