ln-772-error-handler-setup

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ln-772-error-handler-setup

ln-772-error-handler-setup

Type: L3 Worker Category: 7XX Project Bootstrap Parent: ln-770-crosscutting-setup
Configures global error handling for .NET and Python backend applications.

类型: L3 工作流 分类: 7XX 项目初始化 父节点: ln-770-crosscutting-setup
为.NET和Python后端应用配置全局错误处理。

Overview

概述

AspectDetails
InputContext Store from ln-770
OutputException handling middleware and custom exceptions
Stacks.NET (ASP.NET Core Middleware), Python (FastAPI exception handlers)

方面详情
输入来自ln-770的上下文存储
输出异常处理中间件和自定义异常
技术栈.NET (ASP.NET Core Middleware), Python (FastAPI exception handlers)

Phase 1: Receive Context

阶段1:接收上下文

Accept Context Store from coordinator.
Required Context:
  • STACK
    : .NET or Python
  • FRAMEWORK
    : ASP.NET Core or FastAPI
  • PROJECT_ROOT
    : Project directory path
  • ENVIRONMENT
    : Development or Production
Idempotency Check:
  • .NET: Grep for
    GlobalExceptionMiddleware
    or
    UseExceptionHandler
  • Python: Grep for
    @app.exception_handler
    or
    exception_handlers.py
  • If found: Return
    { "status": "skipped" }

接收来自协调器的上下文存储。
必填上下文:
  • STACK
    : .NET 或 Python
  • FRAMEWORK
    : ASP.NET Core 或 FastAPI
  • PROJECT_ROOT
    : 项目目录路径
  • ENVIRONMENT
    : 开发环境或生产环境
幂等性检查:
  • .NET: Grep for
    GlobalExceptionMiddleware
    or
    UseExceptionHandler
  • Python: Grep for
    @app.exception_handler
    or
    exception_handlers.py
  • 若已存在:返回
    { "status": "skipped" }

Phase 2: Research Error Handling Patterns

阶段2:研究错误处理模式

Use MCP tools to get up-to-date documentation.
For .NET:
MCP ref: "ASP.NET Core global exception handling middleware"
Context7: /dotnet/aspnetcore
For Python:
MCP ref: "FastAPI exception handlers custom exceptions"
Context7: /tiangolo/fastapi
Key Patterns to Research:
  1. Middleware pipeline positioning
  2. Exception type mapping to HTTP status codes
  3. ProblemDetails (RFC 7807) format
  4. Development vs Production error details
  5. Logging integration

使用MCP工具获取最新文档。
针对.NET:
MCP ref: "ASP.NET Core global exception handling middleware"
Context7: /dotnet/aspnetcore
针对Python:
MCP ref: "FastAPI exception handlers custom exceptions"
Context7: /tiangolo/fastapi
需研究的关键模式:
  1. 中间件管道定位
  2. 异常类型到HTTP状态码的映射
  3. ProblemDetails (RFC 7807) 格式
  4. 开发环境与生产环境的错误详情差异
  5. 日志集成

Phase 3: Decision Points

阶段3:决策点

Q1: Error Response Format

Q1:错误响应格式

OptionDescription
ProblemDetails (RFC 7807) (Recommended)Standardized format, widely adopted
Custom FormatProject-specific requirements
选项描述
ProblemDetails (RFC 7807)(推荐)标准化格式,被广泛采用
自定义格式符合项目特定需求

Q2: Error Detail Level

Q2:错误详情级别

EnvironmentStack TraceInner ExceptionsRequest Details
Development✓ Show✓ Show✓ Show
Production✗ Hide✗ Hide✗ Hide
环境堆栈跟踪内部异常请求详情
开发环境✓ 显示✓ 显示✓ 显示
生产环境✗ 隐藏✗ 隐藏✗ 隐藏

Q3: Error Taxonomy

Q3:错误分类

Define standard error codes:
CodeHTTP StatusDescription
VALIDATION_ERROR
400Invalid input data
UNAUTHORIZED
401Authentication required
FORBIDDEN
403Insufficient permissions
NOT_FOUND
404Resource not found
CONFLICT
409Resource state conflict
INTERNAL_ERROR
500Unexpected server error

定义标准错误码:
代码HTTP状态码描述
VALIDATION_ERROR
400输入数据无效
UNAUTHORIZED
401需要身份验证
FORBIDDEN
403权限不足
NOT_FOUND
404资源未找到
CONFLICT
409资源状态冲突
INTERNAL_ERROR
500服务器意外错误

Phase 4: Generate Configuration

阶段4:生成配置

.NET Output Files

.NET 输出文件

FilePurpose
Middleware/GlobalExceptionMiddleware.cs
Exception handling middleware
Exceptions/AppException.cs
Base exception class
Exceptions/ValidationException.cs
Validation errors
Exceptions/NotFoundException.cs
Not found errors
Models/ErrorResponse.cs
Error response model
Generation Process:
  1. Use MCP ref to get current ASP.NET Core exception handling patterns
  2. Generate GlobalExceptionMiddleware with:
    • Exception type to HTTP status mapping
    • Logging of exceptions
    • ProblemDetails response format
    • Environment-aware detail level
  3. Generate custom exception classes
Registration Code:
csharp
app.UseMiddleware<GlobalExceptionMiddleware>();
文件用途
Middleware/GlobalExceptionMiddleware.cs
异常处理中间件
Exceptions/AppException.cs
基础异常类
Exceptions/ValidationException.cs
验证错误类
Exceptions/NotFoundException.cs
资源未找到错误类
Models/ErrorResponse.cs
错误响应模型
生成流程:
  1. 使用MCP参考获取当前ASP.NET Core异常处理模式
  2. 生成GlobalExceptionMiddleware,包含:
    • 异常类型到HTTP状态码的映射
    • 异常日志记录
    • ProblemDetails响应格式
    • 感知环境的详情级别
  3. 生成自定义异常类
注册代码:
csharp
app.UseMiddleware<GlobalExceptionMiddleware>();

Python Output Files

Python 输出文件

FilePurpose
exceptions/app_exceptions.py
Custom exception classes
exceptions/handlers.py
FastAPI exception handlers
models/error_response.py
Pydantic error models
Generation Process:
  1. Use MCP ref to get current FastAPI exception handling patterns
  2. Generate exception handlers with:
    • HTTPException handling
    • Custom AppException handling
    • Validation error handling
    • Request validation error handling
  3. Generate custom exception classes
Registration Code:
python
app.add_exception_handler(AppException, app_exception_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)

文件用途
exceptions/app_exceptions.py
自定义异常类
exceptions/handlers.py
FastAPI异常处理器
models/error_response.py
Pydantic错误模型
生成流程:
  1. 使用MCP参考获取当前FastAPI异常处理模式
  2. 生成异常处理器,包含:
    • HTTPException处理
    • 自定义AppException处理
    • 验证错误处理
    • 请求验证错误处理
  3. 生成自定义异常类
注册代码:
python
app.add_exception_handler(AppException, app_exception_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)

Phase 5: Validate

阶段5:验证

Validation Steps:
  1. Syntax check:
    • .NET:
      dotnet build --no-restore
    • Python:
      python -m py_compile exceptions/handlers.py
  2. Test error handling:
    • Create test endpoint that throws exception
    • Verify error response format
    • Check that stack trace hidden in Production
Expected Error Response (ProblemDetails):
json
{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "Validation Error",
  "status": 400,
  "detail": "Invalid input data",
  "instance": "/api/users",
  "errors": [
    { "field": "email", "message": "Invalid email format" }
  ],
  "traceId": "abc-123-def-456"
}

验证步骤:
  1. 语法检查:
    • .NET:
      dotnet build --no-restore
    • Python:
      python -m py_compile exceptions/handlers.py
  2. 测试错误处理:
    • 创建抛出异常的测试端点
    • 验证错误响应格式
    • 检查生产环境中堆栈跟踪是否被隐藏
预期错误响应(ProblemDetails格式):
json
{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "Validation Error",
  "status": 400,
  "detail": "Invalid input data",
  "instance": "/api/users",
  "errors": [
    { "field": "email", "message": "Invalid email format" }
  ],
  "traceId": "abc-123-def-456"
}

Return to Coordinator

返回协调器

json
{
  "status": "success",
  "files_created": [
    "Middleware/GlobalExceptionMiddleware.cs",
    "Exceptions/AppException.cs",
    "Models/ErrorResponse.cs"
  ],
  "packages_added": [],
  "registration_code": "app.UseMiddleware<GlobalExceptionMiddleware>();",
  "message": "Configured global exception handling"
}

json
{
  "status": "success",
  "files_created": [
    "Middleware/GlobalExceptionMiddleware.cs",
    "Exceptions/AppException.cs",
    "Models/ErrorResponse.cs"
  ],
  "packages_added": [],
  "registration_code": "app.UseMiddleware<GlobalExceptionMiddleware>();",
  "message": "Configured global exception handling"
}

Reference Links

参考链接