Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问许可证需确认审计通过

error-sanitization错误清理

Agent Skill

error-sanitization 用于记录任务执行中的错误、用户纠正、经验和能力缺口,适合在 Codex、Claude、Cursor、Gemini CLI 中希望让 Agent 持续沉淀问题、修正和最佳实践时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

517

周安装

22

GitHub Stars

777

下载量

181
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:error-sanitization(错误清理)
来源仓库:https://github.com/dadbodgeoff/drift
仓库路径:skills/error-sanitization
安装命令:
npx skills add https://github.com/dadbodgeoff/drift --skill error-sanitization
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/dadbodgeoff/drift --skill error-sanitization

简介

error-sanitization 确保生产环境中错误消息不暴露敏感信息,全部日志留存服务端。

  • 适用于 API 网关、批处理作业等需对外返回错误但又要保护隐私的场景。
  • 指导如何剥离连接字符串、路径和堆栈轨迹,仅返回通用提示。
  • 安装方式:通过 npx 从 GitHub 仓库添加,需配置日志中间件或拦截器。
  • 必须配合完善的日志收集系统,否则失去调试价值。

SKILL.md

Error Sanitization

Production-safe error handling: log everything server-side, expose nothing sensitive to users.

When to Use This Skill

  • Building APIs that return error messages to clients
  • Handling exceptions in production environments
  • Processing batch operations with partial failures
  • Any system where error messages could leak sensitive information

Core Concepts

Error messages can leak sensitive information including database connection strings, internal file paths, stack traces, API keys, and business logic details. The solution is to always log full error details server-side for debugging while returning only generic, safe messages to users.

The flow is:

  1. Exception occurs
  2. Log FULL error server-side with context
  3. Classify error type
  4. Return GENERIC message to user
  5. Only expose safe, actionable errors (like validation)

Implementation

Python

import os
import logging
from typing import Optional
from fastapi import HTTPException
from pydantic import ValidationError

logger = logging.getLogger(__name__)

class ErrorSanitizer:
    """
    Sanitizes error messages to prevent information leakage.
    """

    SENSITIVE_PATTERNS = [
        "password", "secret", "key", "token", "credential",
        "postgresql://", "mysql://", "mongodb://", "redis://",
        "localhost", "127.0.0.1", "internal", "0.0.0.0",
        "traceback", "exception", "error at", "line ",
        "/home/", "/var/", "/etc/", "C:\\",
        "SUPABASE", "AWS", "STRIPE", "SENDGRID",
    ]

    @staticmethod
    def is_production() -> bool:
        return os.getenv("ENVIRONMENT", "development").lower() == "production"

    @staticmethod
    def sanitize_error(
        e: Exception,
        user_message: str = "Operation failed",
        log_context: Optional[dict] = None
    ) -> str:
        """Sanitize error message for user display."""
        # ALWAYS log full error server-side
        logger.error(
            f"Error occurred: {type(e).__name__}: {str(e)}",
            exc_info=True,
            extra=log_context or {}
        )

        # In development, show more details
        if not ErrorSanitizer.is_production():
            return f"{user_message}: {str(e)}"

        # Validation errors are safe (user input issues)
        if isinstance(e, ValidationError):
            return f"Validation error: {str(e)}"

        # HTTPException with client error (4xx) is safe
        if isinstance(e, HTTPException):
            if 400 <= e.status_code < 500:
                return e.detail
            return user_message

        # Check for sensitive patterns
        error_str = str(e).lower()
        for pattern in ErrorSanitizer.SENSITIVE_PATTERNS:
            if pattern in error_str:
                return user_message

        # Short, simple errors without sensitive patterns might be safe
        if len(str(e)) < 100 and not any(c in str(e) for c in ['/', '\\', '@', ':']):
            return str(e)

        return user_message

    @staticmethod
    def create_http_exception(
        e: Exception,
        status_code: int = 500,
        user_message: str = "Operation failed",
        log_context: Optional[dict] = None
    ) -> HTTPException:
        """Create HTTPException with sanitized error message."""
        safe_message = ErrorSanitizer.sanitize_error(e, user_message, log_context)
        return HTTPException(status_code=status_code, detail=safe_message)

TypeScript

import { Logger } from './logger';

const SENSITIVE_PATTERNS = [
  'password', 'secret', 'key', 'token', 'credential',
  'postgresql://', 'mysql://', 'mongodb://', 'redis://',
  'localhost', '127.0.0.1', 'internal', '0.0.0.0',
  '/home/', '/var/', '/etc/', 'C:\\',
];

interface SanitizeOptions {
  userMessage?: string;
  logContext?: Record<string, unknown>;
}

export class ErrorSanitizer {
  private static isProduction(): boolean {
    return process.env.NODE_ENV === 'production';
  }

  static sanitize(
    error: Error,
    options: SanitizeOptions = {}
  ): string {
    const { userMessage = 'Operation failed', logContext = {} } = options;

    // Always log full error server-side
    Logger.error('Error occurred', {
      name: error.name,
      message: error.message,
      stack: error.stack,
      ...logContext,
    });

    // In development, show more details
    if (!this.isProduction()) {
      return `${userMessage}: ${error.message}`;
    }

    // Check for sensitive patterns
    const errorStr = error.message.toLowerCase();
    for (const pattern of SENSITIVE_PATTERNS) {
      if (errorStr.includes(pattern)) {
        return userMessage;
      }
    }

    // Short, simple errors might be safe
    if (error.message.length < 100 && !/[\/\\@:]/.test(error.message)) {
      return error.message;
    }

    return userMessage;
  }

  static createHttpError(
    error: Error,
    statusCode: number = 500,
    options: SanitizeOptions = {}
  ): { statusCode: number; message: string } {
    return {
      statusCode,
      message: this.sanitize(error, options),
    };
  }
}

Usage Examples

Route Handler

@router.post("/process")
async def process_invoice(invoice_id: str):
    try:
        result = await processor.process(invoice_id)
        return result
    except ValidationError as e:
        # Validation errors are safe to expose
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise  # Re-raise as-is
    except Exception as e:
        # All other errors get sanitized
        raise ErrorSanitizer.create_http_exception(
            e,
            status_code=500,
            user_message="Failed to process invoice",
            log_context={"invoice_id": invoice_id}
        )

Domain-Specific Sanitizers

def sanitize_database_error(e: Exception) -> str:
    return ErrorSanitizer.sanitize_error(
        e,
        user_message="Database operation failed. Please try again.",
        log_context={"error_type": "database"}
    )

def sanitize_api_error(e: Exception, service_name: str = "external service") -> str:
    return ErrorSanitizer.sanitize_error(
        e,
        user_message=f"Failed to communicate with {service_name}.",
        log_context={"error_type": "external_api", "service": service_name}
    )

Batch Operations with Partial Failures

def process_items(items: list[dict]) -> dict:
    failed_items = []

    for idx, item in enumerate(items):
        try:
            process_item(item)
        except Exception as e:
            error_type = classify_error(e)
            failed_items.append({
                "line": idx,
                "description": item['description'][:50],  # Truncate
                "error_type": error_type,
                "message": get_user_friendly_message(error_type)
                # NOTE: Don't include str(e) - might be sensitive
            })

    return {
        "status": "partial_success" if failed_items else "success",
        "failed_items": failed_items
    }

Best Practices

  1. Always log full error details server-side with exc_info=True
  2. Include correlation IDs (request_id, session_id) in logs for tracing
  3. Truncate user input in error messages to prevent log injection
  4. Test error handling in production mode - errors look different in dev vs prod
  5. Monitor "unknown" error rates - high rates indicate missing classification

Common Mistakes

  • Exposing raw exception messages to users in production
  • Forgetting to log the full error before sanitizing
  • Including sensitive data in log messages (passwords, connection strings)
  • Not testing error responses in production mode
  • Trusting that "safe" errors don't contain injected content

Related Patterns

  • exception-taxonomy - Hierarchical exception system with error codes
  • circuit-breaker - Prevent cascading failures
  • error-handling - General error handling patterns

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

36.88%
按下载量换算67

Claude

27.2%
按下载量换算49

Cursor

16.67%
按下载量换算30

Gemini CLI

9.32%
按下载量换算17

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills