[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M69BF6N55FCZ9Y10Q9BJE5VN":3,"skill-same:01M69BF6N55FCZ9Y10Q9BJE5VN":62},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":7,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":29,"publishedAt":33,"linkOnly":34,"markdownContent":35,"markdownBody":36,"frontMatter":37,"refName":38,"commitSha":39,"skillDirectory":40,"forksCount":41,"repositoryHtmlUrl":42,"repositoryHomepageUrl":43,"ownerHtmlUrl":44,"ownerBlogUrl":45,"ownerDescription":46,"updatedAt":47,"install":48,"resources":61},"01M69BF6N55FCZ9Y10Q9BJE5VN","error-handling","统一错误处理系统","统一错误处理系统。在添加 API 端点、修改错误处理、添加前端 API 调用、编写错误相关测试时使用。","microsoft\u002Fdata-formulator","microsoft","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6154722?v=4","01M698VYDXZ6JW5WH3CRV650R8","Microsoft","01M69BF44TK0TP41QE6EZXBGRY",17682,"MIT",null,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdata-formulator\u002Fblob\u002Fmain\u002F.cursor\u002Fskills\u002Ferror-handling\u002FSKILL.md",[19,24],{"categoryNo":20,"categoryName":21,"taxonomyType":22,"taxonomyTypeDesc":23},"01M8BQ6TQZN6R52WBJ9H8NRMQM","软件开发工程师","PROFESSION","适用职业",{"categoryNo":25,"categoryName":26,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8BT7QVANT4709358VEJK53E","代码实现","SCENARIO","使用场景",[30,31,32],"error handling","testing","frontend","2026-11-10 10:12:30",false,"---\nname: error-handling\ndescription: 统一错误处理系统。在添加 API 端点、修改错误处理、添加前端 API 调用、编写错误相关测试时使用。\n---\n\n# Error Handling Skill\n\nUnified error handling system for DF. Use when adding API endpoints, modifying error handling, or adding frontend API calls.\n\n> **Prerequisites**: Read `docs\u002Fdev-guides\u002F7-unified-error-handling.md` before changing API error behavior.\n> Read `docs\u002Fdev-guides\u002F2-log-sanitization.md` when the work involves logging, credentials, external services, or DataLoaders.\n> If your work introduces new error handling patterns or conventions, update this file and related dev-guides accordingly.\n\n## Architecture Overview\n\n```\nFrontend                              Backend\n────────                              ───────\napiClient.ts                          errors.py\n├── apiRequest()    ←── JSON ────     ├── ErrorCode (enum)\n├── streamRequest() ←── NDJSON ──     └── AppError (exception)\n└── parseStreamLine()\n                                      error_handler.py\nerrorCodes.ts                         ├── register_error_handlers(app)\n└── getErrorMessage()                 ├── classify_and_wrap_llm_error()\n                                      └── stream_error_event()\nerrorHandler.ts\n└── handleApiError()                  security\u002Fsanitize.py\n                                      └── classify_llm_error() (internal)\nMessageSnackbar ← dfSlice.messages\n```\n\n## Protocol Snapshot\n\nUse this contract for all new or reworked DF APIs:\n\n| Scenario | HTTP | Shape |\n|----------|------|-------|\n| Non-streaming success | `200` | `{\"status\": \"success\", \"data\": ...}` |\n| Non-streaming business\u002Fvalidation error | `200` | `{\"status\": \"error\", \"error\": {\"code\", \"message\", \"retry\", \"request_id\"}}` |\n| Non-streaming auth\u002Fauthorization error | `401` \u002F `403` | same structured error body |\n| Streaming preflight error | `200` | `application\u002Fjson` + `{\"status\": \"error\", \"error\": ...}` |\n| Streaming in-flight fatal error | `200` | NDJSON line: `{\"type\": \"error\", \"error\": ...}` |\n| No Flask route \u002F too large \u002F unhandled crash | `404` \u002F `413` \u002F `500` | transport-level error |\n\nDo not use HTTP `400`\u002F`422` for application validation errors in new code.\nDo not convert in-flight NDJSON errors to `status: \"error\"`; once the stream has\nstarted, event `type` is the protocol discriminator.\n\n## Backend: Adding a New API Endpoint\n\n### HTTP Status Code Policy\n\n**Application-controlled business and validation errors return HTTP 200** with\n`status: \"error\"` in the body. Only these use non-200:\n- `401`\u002F`403` — auth errors (`AUTH_REQUIRED`, `AUTH_EXPIRED`, `ACCESS_DENIED`)\n- `404` — no matching Flask route\n- `413` — WSGI body limit exceeded\n- `500` — unhandled exception (program bug)\n\n### Non-streaming endpoint\n\n```python\nfrom data_formulator.errors import AppError, ErrorCode\nfrom data_formulator.error_handler import json_ok\n\n@bp.route('\u002Fmy-endpoint', methods=['POST'])\ndef my_endpoint():\n    content = request.get_json()\n    if not content.get('required_field'):\n        raise AppError(ErrorCode.INVALID_REQUEST, \"Missing required_field\")\n\n    try:\n        result = do_work(content)\n    except SomeBusinessError as e:\n        raise AppError(ErrorCode.DATA_LOAD_ERROR, \"Failed to load data\") from e\n    except Exception as e:\n        from data_formulator.error_handler import classify_and_wrap_llm_error\n        raise classify_and_wrap_llm_error(e) from e\n\n    return json_ok(result)\n# Global handler returns: HTTP 200 + {\"status\": \"error\", \"error\": {code, message, retry}}\n# Auth errors (AUTH_REQUIRED\u002FAUTH_EXPIRED\u002FACCESS_DENIED) return 401\u002F403\n```\n\nLegacy `{\"status\": \"error\", \"message\": \"...\"}`, `error_message`, bare `{error}`,\nand `status: \"ok\"` responses are historical formats. Do not add new compatibility\nbranches for them; migrate the route to `json_ok()` \u002F `AppError` before using\n`apiRequest()`.\n\n### Streaming endpoint\n\nValidation MUST be outside the generator. Failures return 200 JSON (not NDJSON).\n\n```python\nfrom data_formulator.errors import AppError, ErrorCode\nfrom data_formulator.error_handler import (\n    classify_and_wrap_llm_error,\n    stream_error_event,\n    stream_preflight_error,\n)\n\n@bp.route('\u002Fmy-stream', methods=['POST'])\ndef my_stream():\n    if not request.is_json:\n        return stream_preflight_error(\n            AppError(ErrorCode.INVALID_REQUEST, \"Invalid request\")\n        )\n\n    content = request.get_json()\n    client = get_client(content['model'])\n\n    def generate():\n        try:\n            for event in agent.run(...):\n                yield json.dumps(event, ensure_ascii=False) + \"\\n\"\n        except Exception as e:\n            yield stream_error_event(classify_and_wrap_llm_error(e))\n\n    return Response(stream_with_context(generate()), mimetype='application\u002Fx-ndjson')\n```\n\nStreaming runtime errors intentionally use `{\"type\": \"error\", \"error\": ...}`.\nThey cannot use a top-level `status` envelope because the HTTP response and NDJSON\nevent stream have already started.\n\n## Frontend: Consuming an API\n\n### Non-streaming\n\n```typescript\nimport { apiRequest } from '..\u002Fapp\u002FapiClient';\nimport { handleApiError } from '..\u002Fapp\u002FerrorHandler';\n\ntry {\n    const { data } = await apiRequest\u003CResponseType>(getUrls().MY_ENDPOINT, {\n        method: 'POST',\n        body: JSON.stringify(payload),\n        headers: { 'Content-Type': 'application\u002Fjson' },\n    });\n} catch (e) {\n    handleApiError(e, 'MyComponent');\n}\n```\n\nFor UI loading state, model the request lifecycle explicitly with\n`LoadableState` from `src\u002Fapp\u002FloadableState.ts`. Do not infer loading from\nmissing data (`!data`), because failed requests may legitimately leave data\nempty while loading has ended.\n\n### Streaming\n\n```typescript\nimport { streamRequest } from '..\u002Fapp\u002FapiClient';\nimport { handleApiError } from '..\u002Fapp\u002FerrorHandler';\n\ntry {\n    for await (const event of streamRequest(url, options, abortController.signal)) {\n        switch (event.type) {\n            case 'text_delta':\n                break;\n            case 'error':\n                \u002F\u002F Error arrived mid-stream — show inline in component.\n                break;\n            case 'done':\n                break;\n        }\n    }\n} catch (e) {\n    handleApiError(e, 'MyComponent');\n}\n```\n\n### With callbacks\n\n```typescript\nhandleApiError(e, 'MyComponent', {\n    onAuth: () => redirectToLogin(),        \u002F\u002F AUTH_REQUIRED \u002F AUTH_EXPIRED\n    onRetryable: () => retryOperation(),    \u002F\u002F LLM_RATE_LIMIT \u002F LLM_TIMEOUT\n    silent: true,                           \u002F\u002F don't show Snackbar (component handles display)\n});\n```\n\n### Migration and special cases\n\nDF API consumers should use `apiRequest()` \u002F `streamRequest()` and\n`handleApiError()`. Direct `fetchWithIdentity()` is for lower-level client helpers\nand explicit protocol exceptions such as file downloads, blob\u002FCSV responses,\nOIDC redirects, SPA fallback, or third-party URLs.\n\nDo not apply the normal JSON API protocol mechanically to file downloads \u002F CSV\nstreaming, SPA fallback, OIDC redirect flows, frontend fetches to third-party\nURLs, or errors after a streaming response has already started. Check the route's\nprotocol first, then preserve safe error bodies and avoid `str(exc)` exposure.\n\n## Adding a New Error Code\n\n1. **Backend** — Add to `py-src\u002Fdata_formulator\u002Ferrors.py` `ErrorCode`:\n   ```python\n   MY_NEW_ERROR = \"MY_NEW_ERROR\"\n   ```\n   No HTTP mapping needed — defaults to HTTP 200. Only add to `ERROR_CODE_HTTP_STATUS` if it's an auth code.\n\n2. **Frontend mapping** — Add to `src\u002Fapp\u002FerrorCodes.ts` `ERROR_CODE_I18N_MAP`:\n   ```typescript\n   MY_NEW_ERROR: 'errors.myNewError',\n   ```\n\n3. **Translations** — Add to both locale files:\n   - `src\u002Fi18n\u002Flocales\u002Fen\u002Ferrors.json`: `\"myNewError\": \"English message\"`\n   - `src\u002Fi18n\u002Flocales\u002Fzh\u002Ferrors.json`: `\"myNewError\": \"中文消息\"`\n\n## Migrated Endpoints Reference\n\nAll streaming endpoints are now on the unified protocol:\n\n| Endpoint | Format | Notes |\n|----------|--------|-------|\n| `\u002Fdata-agent-streaming` | NDJSON + `stream_error_event()` | Emits top-level `type` events; errors use `{type:\"error\", error:{...}}` |\n| `\u002Fget-recommendation-questions` | NDJSON + `stream_error_event()` | Was `error: {json}` prefix |\n| `\u002Fgenerate-report-chat` | Pure NDJSON + `stream_error_event()` | Was SSE `data: {json}` prefix |\n| `\u002Fdata-loading-chat` | NDJSON + `stream_error_event()` | `str(e)` removed |\n| `\u002Fclean-data-stream` | NDJSON + `stream_error_event()` | Was `\\n{json}\\n` format |\n\nNon-streaming endpoints:\n\n| Endpoint | Error Format | Notes |\n|----------|-------------|-------|\n| `\u002Fchart-insight` | `AppError` → HTTP 200 + `{status:\"error\", error:{code,message,retry}}` | Fully migrated. Frontend uses `fetchChartInsight` rejected reducer. |\n| All migrated endpoints | `AppError` → HTTP 200 + unified error body | credentials, knowledge, sessions, tables, agents |\n| `\u002Fderive-data`, `\u002Frefine-data`, `\u002Fsort-data`, `\u002Fprocess-data-on-load`, `\u002Ftest-model` | `json_ok()` \u002F `AppError` | Migrated to new format |\n\n## Empty Catch Policy\n\nNot all `.catch(() => {})` are bugs. Use this decision tree:\n\n1. **User-initiated action** (delete, refresh, submit) → must notify with `addMessages` or `handleApiError()`\n2. **Background\u002Fbest-effort fetch** (connector list on mount, session list) → OK to swallow, but add a comment\n3. **RTK thunks** → always add `.rejected` handler with `addMessages`\n4. **AbortError** → filter out with `if (action.error?.name !== 'AbortError')`\n\n## Frontend Stream Parsing Pattern\n\nWhen consuming a migrated streaming endpoint, handle the current NDJSON event\nformat directly:\n\n```typescript\nconst data = JSON.parse(line);\nif (data.type === 'error') {\n    const errMsg = data.error?.message || 'Unknown error';\n    \u002F\u002F show to user...\n}\n```\n\n## Backend: Database\u002FWorkspace Errors (tables.py)\n\nFor table CRUD endpoints, use the specialized classifier:\n\n```python\nfrom data_formulator.routes.tables import classify_and_raise_db_error\n\n@tables_bp.route('\u002Fmy-table-op', methods=['POST'])\ndef my_table_op():\n    try:\n        result = workspace.do_something()\n        return jsonify({\"status\": \"success\", \"data\": result})\n    except Exception as e:\n        classify_and_raise_db_error(e)\n```\n\n`classify_and_raise_db_error` maps common DB errors to appropriate `AppError` codes\n(returned as HTTP 200 by the global handler, except ACCESS_DENIED → 403):\n- \"Table does not exist\" → `TABLE_NOT_FOUND` (HTTP 200)\n- \"Table already exists\" → `INVALID_REQUEST` (HTTP 200)\n- \"Permission denied\" → `ACCESS_DENIED` (HTTP 403)\n- Other → `CONNECTOR_ERROR` (HTTP 200)\n\n## Backend: Connector Errors (data_connector.py)\n\nFor connector endpoints, use:\n\n```python\nfrom data_formulator.data_connector import classify_and_raise_connector_error\n\nexcept Exception as e:\n    classify_and_raise_connector_error(e, operation=\"preview\")\n```\n\nConnector\u002FDataLoader classification is intentionally simple and lives in\n`data_formulator.data_loader.connector_errors`. It maps common failures to a\nsmall stable set: `INVALID_REQUEST`, `CONNECTOR_AUTH_FAILED`, `AUTH_EXPIRED`,\n`ACCESS_DENIED`, `DB_CONNECTION_FAILED`, `DB_QUERY_ERROR`, `DATA_LOAD_ERROR`,\nor `CONNECTOR_ERROR`. Do not add endpoint-local string matching unless the\nclassifier cannot reasonably cover the category.\n\nAll JSON errors include `error.request_id` and an `X-Request-Id` response\nheader. Show\u002Fcopy this ID for users when reporting backend failures; do not\nshow raw exception text in production. Unhandled 500 responses must never\ninclude raw tracebacks, even in debug mode; return a safe category plus\n`request_id` and keep full stack traces in server logs only.\n\n## Debugging Error Propagation\n\nWhen an error isn't reaching the frontend:\n\n1. **Check backend logs** — is the error logged?\n2. **Check response format**:\n   - Non-streaming: `{\"status\": \"error\", \"error\": {\"code\": ..., \"message\": ...}}`\n   - Streaming: one line `{\"type\": \"error\", \"error\": {\"code\": ..., \"message\": ...}}`\n3. **Check Content-Type** — streaming must be `application\u002Fx-ndjson`, not `application\u002Fjson` or `text\u002Fevent-stream`\n4. **Check frontend parser** — is the consumer looking for `data.type === 'error'`?\n5. **Check global handler** — verify `register_error_handlers(app)` is called in `app.py`\n6. **Check blueprint handlers** — blueprint-level `errorhandler(Exception)` takes priority over global handlers\n\nLegacy `message` \u002F `error_message` bodies are protocol violations on migrated API paths.\n\n## Log Sanitization (Sensitive Data in Server Logs)\n\nServer-side logs must never leak passwords, tokens, API keys, or connection strings.\nThe project uses a defense-in-depth approach with two layers.\n\n### Layer 1: Explicit Utilities (call-site)\n\n```python\nfrom data_formulator.security.log_sanitizer import (\n    sanitize_url, sanitize_params, redact_token,\n)\n\n# Dict with credentials → sanitize_params()\nlog.info(\"Connecting with: %s\", sanitize_params(params))\n\n# URL that may embed credentials → sanitize_url()\nlogger.info(\"Issuer: %s\", sanitize_url(issuer_url))\n\n# Token\u002FAPI key → redact_token()\nlogger.debug(\"Token: %s\", redact_token(token))\n```\n\n### Layer 2: SensitiveDataFilter (global safety net)\n\nRegistered in `app.py:configure_logging()`. Automatically redacts:\n- URL credentials (`:\u002F\u002Fuser:pass@host`)\n- `Bearer` tokens\n- `password=xxx`, `api_key=xxx`, `secret=xxx` patterns\n- JWT-like base64 strings\n- Python dict repr with sensitive keys\n\nDisable with `LOG_SANITIZE=false` for local debugging only.\n\n### When to Use What\n\n| Data | Utility | Why not just filter? |\n|------|---------|---------------------|\n| `dict` with password keys | `sanitize_params()` | Filter can't identify arbitrary password values in dict repr |\n| URL from config\u002Fenv | `sanitize_url()` | Explicit is clearer; filter is backup |\n| Token\u002Fkey value | `redact_token()` | Explicit is clearer; filter is backup |\n| Normal text | Nothing | Filter handles edge cases |\n\n### New Module Checklist\n\nWhen adding a module that handles credentials or external services:\n\n1. Audit all `logger.*()` calls for credential\u002FURL\u002Ftoken logging\n2. Use `sanitize_params()` for dicts, `sanitize_url()` for URLs, `redact_token()` for tokens\n3. Prefer `type(exc).__name__` over `str(exc)` in warning-level logs\n4. If introducing new credential key names, add to `SENSITIVE_KEYS` in `log_sanitizer.py`\n\n## Key Files\n\n| File | Purpose |\n|------|---------|\n| `py-src\u002Fdata_formulator\u002Ferrors.py` | `ErrorCode` enum + `AppError` exception |\n| `py-src\u002Fdata_formulator\u002Ferror_handler.py` | Global handlers, `classify_and_wrap_llm_error`, `stream_error_event` |\n| `py-src\u002Fdata_formulator\u002Fsecurity\u002Flog_sanitizer.py` | `sanitize_url`, `sanitize_params`, `redact_token`, `SensitiveDataFilter` |\n| `py-src\u002Fdata_formulator\u002Froutes\u002Ftables.py` | `classify_and_raise_db_error` (database\u002Fworkspace errors) |\n| `py-src\u002Fdata_formulator\u002Fdata_connector.py` | `classify_and_raise_connector_error` (connector errors) |\n| `py-src\u002Fdata_formulator\u002Fsecurity\u002Fsanitize.py` | `classify_llm_error` (internal), `sanitize_error_message` |\n| `src\u002Fapp\u002FapiClient.ts` | `apiRequest`, `streamRequest`, `parseStreamLine`, `ApiRequestError` |\n| `src\u002Fapp\u002FerrorHandler.ts` | `handleApiError` |\n| `src\u002Fapp\u002FerrorCodes.ts` | `ERROR_CODE_I18N_MAP`, `getErrorMessage` |\n| `src\u002Fi18n\u002Flocales\u002F{en,zh}\u002Ferrors.json` | Error message translations |\n","# Error Handling Skill\n\nUnified error handling system for DF. Use when adding API endpoints, modifying error handling, or adding frontend API calls.\n\n> **Prerequisites**: Read `docs\u002Fdev-guides\u002F7-unified-error-handling.md` before changing API error behavior.\n> Read `docs\u002Fdev-guides\u002F2-log-sanitization.md` when the work involves logging, credentials, external services, or DataLoaders.\n> If your work introduces new error handling patterns or conventions, update this file and related dev-guides accordingly.\n\n## Architecture Overview\n\n```\nFrontend                              Backend\n────────                              ───────\napiClient.ts                          errors.py\n├── apiRequest()    ←── JSON ────     ├── ErrorCode (enum)\n├── streamRequest() ←── NDJSON ──     └── AppError (exception)\n└── parseStreamLine()\n                                      error_handler.py\nerrorCodes.ts                         ├── register_error_handlers(app)\n└── getErrorMessage()                 ├── classify_and_wrap_llm_error()\n                                      └── stream_error_event()\nerrorHandler.ts\n└── handleApiError()                  security\u002Fsanitize.py\n                                      └── classify_llm_error() (internal)\nMessageSnackbar ← dfSlice.messages\n```\n\n## Protocol Snapshot\n\nUse this contract for all new or reworked DF APIs:\n\n| Scenario | HTTP | Shape |\n|----------|------|-------|\n| Non-streaming success | `200` | `{\"status\": \"success\", \"data\": ...}` |\n| Non-streaming business\u002Fvalidation error | `200` | `{\"status\": \"error\", \"error\": {\"code\", \"message\", \"retry\", \"request_id\"}}` |\n| Non-streaming auth\u002Fauthorization error | `401` \u002F `403` | same structured error body |\n| Streaming preflight error | `200` | `application\u002Fjson` + `{\"status\": \"error\", \"error\": ...}` |\n| Streaming in-flight fatal error | `200` | NDJSON line: `{\"type\": \"error\", \"error\": ...}` |\n| No Flask route \u002F too large \u002F unhandled crash | `404` \u002F `413` \u002F `500` | transport-level error |\n\nDo not use HTTP `400`\u002F`422` for application validation errors in new code.\nDo not convert in-flight NDJSON errors to `status: \"error\"`; once the stream has\nstarted, event `type` is the protocol discriminator.\n\n## Backend: Adding a New API Endpoint\n\n### HTTP Status Code Policy\n\n**Application-controlled business and validation errors return HTTP 200** with\n`status: \"error\"` in the body. Only these use non-200:\n- `401`\u002F`403` — auth errors (`AUTH_REQUIRED`, `AUTH_EXPIRED`, `ACCESS_DENIED`)\n- `404` — no matching Flask route\n- `413` — WSGI body limit exceeded\n- `500` — unhandled exception (program bug)\n\n### Non-streaming endpoint\n\n```python\nfrom data_formulator.errors import AppError, ErrorCode\nfrom data_formulator.error_handler import json_ok\n\n@bp.route('\u002Fmy-endpoint', methods=['POST'])\ndef my_endpoint():\n    content = request.get_json()\n    if not content.get('required_field'):\n        raise AppError(ErrorCode.INVALID_REQUEST, \"Missing required_field\")\n\n    try:\n        result = do_work(content)\n    except SomeBusinessError as e:\n        raise AppError(ErrorCode.DATA_LOAD_ERROR, \"Failed to load data\") from e\n    except Exception as e:\n        from data_formulator.error_handler import classify_and_wrap_llm_error\n        raise classify_and_wrap_llm_error(e) from e\n\n    return json_ok(result)\n# Global handler returns: HTTP 200 + {\"status\": \"error\", \"error\": {code, message, retry}}\n# Auth errors (AUTH_REQUIRED\u002FAUTH_EXPIRED\u002FACCESS_DENIED) return 401\u002F403\n```\n\nLegacy `{\"status\": \"error\", \"message\": \"...\"}`, `error_message`, bare `{error}`,\nand `status: \"ok\"` responses are historical formats. Do not add new compatibility\nbranches for them; migrate the route to `json_ok()` \u002F `AppError` before using\n`apiRequest()`.\n\n### Streaming endpoint\n\nValidation MUST be outside the generator. Failures return 200 JSON (not NDJSON).\n\n```python\nfrom data_formulator.errors import AppError, ErrorCode\nfrom data_formulator.error_handler import (\n    classify_and_wrap_llm_error,\n    stream_error_event,\n    stream_preflight_error,\n)\n\n@bp.route('\u002Fmy-stream', methods=['POST'])\ndef my_stream():\n    if not request.is_json:\n        return stream_preflight_error(\n            AppError(ErrorCode.INVALID_REQUEST, \"Invalid request\")\n        )\n\n    content = request.get_json()\n    client = get_client(content['model'])\n\n    def generate():\n        try:\n            for event in agent.run(...):\n                yield json.dumps(event, ensure_ascii=False) + \"\\n\"\n        except Exception as e:\n            yield stream_error_event(classify_and_wrap_llm_error(e))\n\n    return Response(stream_with_context(generate()), mimetype='application\u002Fx-ndjson')\n```\n\nStreaming runtime errors intentionally use `{\"type\": \"error\", \"error\": ...}`.\nThey cannot use a top-level `status` envelope because the HTTP response and NDJSON\nevent stream have already started.\n\n## Frontend: Consuming an API\n\n### Non-streaming\n\n```typescript\nimport { apiRequest } from '..\u002Fapp\u002FapiClient';\nimport { handleApiError } from '..\u002Fapp\u002FerrorHandler';\n\ntry {\n    const { data } = await apiRequest\u003CResponseType>(getUrls().MY_ENDPOINT, {\n        method: 'POST',\n        body: JSON.stringify(payload),\n        headers: { 'Content-Type': 'application\u002Fjson' },\n    });\n} catch (e) {\n    handleApiError(e, 'MyComponent');\n}\n```\n\nFor UI loading state, model the request lifecycle explicitly with\n`LoadableState` from `src\u002Fapp\u002FloadableState.ts`. Do not infer loading from\nmissing data (`!data`), because failed requests may legitimately leave data\nempty while loading has ended.\n\n### Streaming\n\n```typescript\nimport { streamRequest } from '..\u002Fapp\u002FapiClient';\nimport { handleApiError } from '..\u002Fapp\u002FerrorHandler';\n\ntry {\n    for await (const event of streamRequest(url, options, abortController.signal)) {\n        switch (event.type) {\n            case 'text_delta':\n                break;\n            case 'error':\n                \u002F\u002F Error arrived mid-stream — show inline in component.\n                break;\n            case 'done':\n                break;\n        }\n    }\n} catch (e) {\n    handleApiError(e, 'MyComponent');\n}\n```\n\n### With callbacks\n\n```typescript\nhandleApiError(e, 'MyComponent', {\n    onAuth: () => redirectToLogin(),        \u002F\u002F AUTH_REQUIRED \u002F AUTH_EXPIRED\n    onRetryable: () => retryOperation(),    \u002F\u002F LLM_RATE_LIMIT \u002F LLM_TIMEOUT\n    silent: true,                           \u002F\u002F don't show Snackbar (component handles display)\n});\n```\n\n### Migration and special cases\n\nDF API consumers should use `apiRequest()` \u002F `streamRequest()` and\n`handleApiError()`. Direct `fetchWithIdentity()` is for lower-level client helpers\nand explicit protocol exceptions such as file downloads, blob\u002FCSV responses,\nOIDC redirects, SPA fallback, or third-party URLs.\n\nDo not apply the normal JSON API protocol mechanically to file downloads \u002F CSV\nstreaming, SPA fallback, OIDC redirect flows, frontend fetches to third-party\nURLs, or errors after a streaming response has already started. Check the route's\nprotocol first, then preserve safe error bodies and avoid `str(exc)` exposure.\n\n## Adding a New Error Code\n\n1. **Backend** — Add to `py-src\u002Fdata_formulator\u002Ferrors.py` `ErrorCode`:\n   ```python\n   MY_NEW_ERROR = \"MY_NEW_ERROR\"\n   ```\n   No HTTP mapping needed — defaults to HTTP 200. Only add to `ERROR_CODE_HTTP_STATUS` if it's an auth code.\n\n2. **Frontend mapping** — Add to `src\u002Fapp\u002FerrorCodes.ts` `ERROR_CODE_I18N_MAP`:\n   ```typescript\n   MY_NEW_ERROR: 'errors.myNewError',\n   ```\n\n3. **Translations** — Add to both locale files:\n   - `src\u002Fi18n\u002Flocales\u002Fen\u002Ferrors.json`: `\"myNewError\": \"English message\"`\n   - `src\u002Fi18n\u002Flocales\u002Fzh\u002Ferrors.json`: `\"myNewError\": \"中文消息\"`\n\n## Migrated Endpoints Reference\n\nAll streaming endpoints are now on the unified protocol:\n\n| Endpoint | Format | Notes |\n|----------|--------|-------|\n| `\u002Fdata-agent-streaming` | NDJSON + `stream_error_event()` | Emits top-level `type` events; errors use `{type:\"error\", error:{...}}` |\n| `\u002Fget-recommendation-questions` | NDJSON + `stream_error_event()` | Was `error: {json}` prefix |\n| `\u002Fgenerate-report-chat` | Pure NDJSON + `stream_error_event()` | Was SSE `data: {json}` prefix |\n| `\u002Fdata-loading-chat` | NDJSON + `stream_error_event()` | `str(e)` removed |\n| `\u002Fclean-data-stream` | NDJSON + `stream_error_event()` | Was `\\n{json}\\n` format |\n\nNon-streaming endpoints:\n\n| Endpoint | Error Format | Notes |\n|----------|-------------|-------|\n| `\u002Fchart-insight` | `AppError` → HTTP 200 + `{status:\"error\", error:{code,message,retry}}` | Fully migrated. Frontend uses `fetchChartInsight` rejected reducer. |\n| All migrated endpoints | `AppError` → HTTP 200 + unified error body | credentials, knowledge, sessions, tables, agents |\n| `\u002Fderive-data`, `\u002Frefine-data`, `\u002Fsort-data`, `\u002Fprocess-data-on-load`, `\u002Ftest-model` | `json_ok()` \u002F `AppError` | Migrated to new format |\n\n## Empty Catch Policy\n\nNot all `.catch(() => {})` are bugs. Use this decision tree:\n\n1. **User-initiated action** (delete, refresh, submit) → must notify with `addMessages` or `handleApiError()`\n2. **Background\u002Fbest-effort fetch** (connector list on mount, session list) → OK to swallow, but add a comment\n3. **RTK thunks** → always add `.rejected` handler with `addMessages`\n4. **AbortError** → filter out with `if (action.error?.name !== 'AbortError')`\n\n## Frontend Stream Parsing Pattern\n\nWhen consuming a migrated streaming endpoint, handle the current NDJSON event\nformat directly:\n\n```typescript\nconst data = JSON.parse(line);\nif (data.type === 'error') {\n    const errMsg = data.error?.message || 'Unknown error';\n    \u002F\u002F show to user...\n}\n```\n\n## Backend: Database\u002FWorkspace Errors (tables.py)\n\nFor table CRUD endpoints, use the specialized classifier:\n\n```python\nfrom data_formulator.routes.tables import classify_and_raise_db_error\n\n@tables_bp.route('\u002Fmy-table-op', methods=['POST'])\ndef my_table_op():\n    try:\n        result = workspace.do_something()\n        return jsonify({\"status\": \"success\", \"data\": result})\n    except Exception as e:\n        classify_and_raise_db_error(e)\n```\n\n`classify_and_raise_db_error` maps common DB errors to appropriate `AppError` codes\n(returned as HTTP 200 by the global handler, except ACCESS_DENIED → 403):\n- \"Table does not exist\" → `TABLE_NOT_FOUND` (HTTP 200)\n- \"Table already exists\" → `INVALID_REQUEST` (HTTP 200)\n- \"Permission denied\" → `ACCESS_DENIED` (HTTP 403)\n- Other → `CONNECTOR_ERROR` (HTTP 200)\n\n## Backend: Connector Errors (data_connector.py)\n\nFor connector endpoints, use:\n\n```python\nfrom data_formulator.data_connector import classify_and_raise_connector_error\n\nexcept Exception as e:\n    classify_and_raise_connector_error(e, operation=\"preview\")\n```\n\nConnector\u002FDataLoader classification is intentionally simple and lives in\n`data_formulator.data_loader.connector_errors`. It maps common failures to a\nsmall stable set: `INVALID_REQUEST`, `CONNECTOR_AUTH_FAILED`, `AUTH_EXPIRED`,\n`ACCESS_DENIED`, `DB_CONNECTION_FAILED`, `DB_QUERY_ERROR`, `DATA_LOAD_ERROR`,\nor `CONNECTOR_ERROR`. Do not add endpoint-local string matching unless the\nclassifier cannot reasonably cover the category.\n\nAll JSON errors include `error.request_id` and an `X-Request-Id` response\nheader. Show\u002Fcopy this ID for users when reporting backend failures; do not\nshow raw exception text in production. Unhandled 500 responses must never\ninclude raw tracebacks, even in debug mode; return a safe category plus\n`request_id` and keep full stack traces in server logs only.\n\n## Debugging Error Propagation\n\nWhen an error isn't reaching the frontend:\n\n1. **Check backend logs** — is the error logged?\n2. **Check response format**:\n   - Non-streaming: `{\"status\": \"error\", \"error\": {\"code\": ..., \"message\": ...}}`\n   - Streaming: one line `{\"type\": \"error\", \"error\": {\"code\": ..., \"message\": ...}}`\n3. **Check Content-Type** — streaming must be `application\u002Fx-ndjson`, not `application\u002Fjson` or `text\u002Fevent-stream`\n4. **Check frontend parser** — is the consumer looking for `data.type === 'error'`?\n5. **Check global handler** — verify `register_error_handlers(app)` is called in `app.py`\n6. **Check blueprint handlers** — blueprint-level `errorhandler(Exception)` takes priority over global handlers\n\nLegacy `message` \u002F `error_message` bodies are protocol violations on migrated API paths.\n\n## Log Sanitization (Sensitive Data in Server Logs)\n\nServer-side logs must never leak passwords, tokens, API keys, or connection strings.\nThe project uses a defense-in-depth approach with two layers.\n\n### Layer 1: Explicit Utilities (call-site)\n\n```python\nfrom data_formulator.security.log_sanitizer import (\n    sanitize_url, sanitize_params, redact_token,\n)\n\n# Dict with credentials → sanitize_params()\nlog.info(\"Connecting with: %s\", sanitize_params(params))\n\n# URL that may embed credentials → sanitize_url()\nlogger.info(\"Issuer: %s\", sanitize_url(issuer_url))\n\n# Token\u002FAPI key → redact_token()\nlogger.debug(\"Token: %s\", redact_token(token))\n```\n\n### Layer 2: SensitiveDataFilter (global safety net)\n\nRegistered in `app.py:configure_logging()`. Automatically redacts:\n- URL credentials (`:\u002F\u002Fuser:pass@host`)\n- `Bearer` tokens\n- `password=xxx`, `api_key=xxx`, `secret=xxx` patterns\n- JWT-like base64 strings\n- Python dict repr with sensitive keys\n\nDisable with `LOG_SANITIZE=false` for local debugging only.\n\n### When to Use What\n\n| Data | Utility | Why not just filter? |\n|------|---------|---------------------|\n| `dict` with password keys | `sanitize_params()` | Filter can't identify arbitrary password values in dict repr |\n| URL from config\u002Fenv | `sanitize_url()` | Explicit is clearer; filter is backup |\n| Token\u002Fkey value | `redact_token()` | Explicit is clearer; filter is backup |\n| Normal text | Nothing | Filter handles edge cases |\n\n### New Module Checklist\n\nWhen adding a module that handles credentials or external services:\n\n1. Audit all `logger.*()` calls for credential\u002FURL\u002Ftoken logging\n2. Use `sanitize_params()` for dicts, `sanitize_url()` for URLs, `redact_token()` for tokens\n3. Prefer `type(exc).__name__` over `str(exc)` in warning-level logs\n4. If introducing new credential key names, add to `SENSITIVE_KEYS` in `log_sanitizer.py`\n\n## Key Files\n\n| File | Purpose |\n|------|---------|\n| `py-src\u002Fdata_formulator\u002Ferrors.py` | `ErrorCode` enum + `AppError` exception |\n| `py-src\u002Fdata_formulator\u002Ferror_handler.py` | Global handlers, `classify_and_wrap_llm_error`, `stream_error_event` |\n| `py-src\u002Fdata_formulator\u002Fsecurity\u002Flog_sanitizer.py` | `sanitize_url`, `sanitize_params`, `redact_token`, `SensitiveDataFilter` |\n| `py-src\u002Fdata_formulator\u002Froutes\u002Ftables.py` | `classify_and_raise_db_error` (database\u002Fworkspace errors) |\n| `py-src\u002Fdata_formulator\u002Fdata_connector.py` | `classify_and_raise_connector_error` (connector errors) |\n| `py-src\u002Fdata_formulator\u002Fsecurity\u002Fsanitize.py` | `classify_llm_error` (internal), `sanitize_error_message` |\n| `src\u002Fapp\u002FapiClient.ts` | `apiRequest`, `streamRequest`, `parseStreamLine`, `ApiRequestError` |\n| `src\u002Fapp\u002FerrorHandler.ts` | `handleApiError` |\n| `src\u002Fapp\u002FerrorCodes.ts` | `ERROR_CODE_I18N_MAP`, `getErrorMessage` |\n| `src\u002Fi18n\u002Flocales\u002F{en,zh}\u002Ferrors.json` | Error message translations |\n",{"name":5,"description":7},"main","5477f0e236426dc8f74a498ec400414fba7fbc0f",".cursor\u002Fskills\u002Ferror-handling",1745,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdata-formulator","https:\u002F\u002Fdata-formulator.ai\u002F","https:\u002F\u002Fgithub.com\u002Fmicrosoft","https:\u002F\u002Fopensource.microsoft.com","Open source projects and samples from Microsoft","2026-11-09 22:13:49",{"source":8,"skillName":5,"commands":49,"prompt":59,"zipAvailable":60},[50,53,56],{"tool":51,"command":52},"npx","npx skills add microsoft\u002Fdata-formulator --skill error-handling",{"tool":54,"command":55},"bunx","bunx skills add microsoft\u002Fdata-formulator --skill error-handling",{"tool":57,"command":58},"pnpm","pnpm dlx skills add microsoft\u002Fdata-formulator --skill error-handling","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdata-formulator\u002Fblob\u002Fmain\u002F.cursor\u002Fskills\u002Ferror-handling\u002FSKILL.md",true,[],[63,82,97,107,119,132],{"skillNo":64,"name":65,"nameZh":66,"description":67,"descriptionZh":68,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":69,"categories":70,"keywords":77,"publishedAt":33},"01M69BFJ823DGYDZQMYBFSPJAW","report","Markdown 报告生成","Turn an exploration (threads, findings, charts) into a single Markdown report — note, blog post, executive summary, KPI dashboard, slide brief, or multi-section analytical report, with embedded charts.","将一次探索（线程、发现、图表）转换为单篇 Markdown 报告——笔记、博客文章、执行摘要、KPI 仪表板、幻灯片简报或多章节分析报告，并嵌入图表。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdata-formulator\u002Fblob\u002Fmain\u002Fpy-src\u002Fdata_formulator\u002Fanalyst\u002Fskills\u002Freport\u002FSKILL.md",[71,74],{"categoryNo":72,"categoryName":73,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8BQGD4CMBM6B4PWSM1NXGT9","数据分析与报告",{"categoryNo":75,"categoryName":76,"taxonomyType":22,"taxonomyTypeDesc":23},"01M8BQGD5CX980XNXCJKQF70BY","数据分析师",[65,78,79,80,81],"summarize","visualize","dashboard","executive summary",{"skillNo":83,"name":84,"nameZh":85,"description":86,"descriptionZh":87,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":88,"categories":89,"keywords":92,"publishedAt":33},"01M69BFGGPGA5AK2V3N6PM2EXY","data-loading","数据源发现与加载","Discover connected data sources, add new data connectors through a user-confirmed form, inspect table metadata, and run bounded read-only probes when the current workspace data is insufficient.","发现已连接的数据源，通过用户确认的表单添加新的数据连接器，检查表元数据，并在当前工作区数据不足时运行有界的只读探测。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdata-formulator\u002Fblob\u002Fmain\u002Fpy-src\u002Fdata_formulator\u002Fanalyst\u002Fskills\u002Fdata_loading\u002FSKILL.md",[90,91],{"categoryNo":72,"categoryName":73,"taxonomyType":27,"taxonomyTypeDesc":28},{"categoryNo":75,"categoryName":76,"taxonomyType":22,"taxonomyTypeDesc":23},[93,94,95,96],"data loading","connectors","connect","run",{"skillNo":98,"name":84,"nameZh":85,"description":86,"descriptionZh":99,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":100,"categories":101,"keywords":106,"publishedAt":33},"01M69BFEDNAV78CW1QBH8AFEVT","发现已连接的数据源，通过用户确认的表单添加新的数据连接器，检查表元数据，并在当前工作区数据不足时运行有界只读探测。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdata-formulator\u002Fblob\u002Fmain\u002Fpy-src\u002Fdata_formulator\u002Fanalyst\u002Fskills\u002Fdata-loading\u002FSKILL.md",[102,103],{"categoryNo":75,"categoryName":76,"taxonomyType":22,"taxonomyTypeDesc":23},{"categoryNo":104,"categoryName":105,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8BWWFZDF3GR3XDG2G0W3XCJ","数据治理与目录管理",[93,94,95,96],{"skillNo":108,"name":109,"nameZh":110,"description":111,"descriptionZh":112,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":113,"categories":114,"keywords":117,"publishedAt":33},"01M69BFCDH9Z63K4ND9MXB07H5","core","分析师内置能力与工具","The analyst's built-in capabilities: data-inspection tools and the always-available actions (visualize and ask_user).","分析师的内置能力：数据检查工具以及始终可用的操作（可视化 visualize 和询问用户 ask_user）。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdata-formulator\u002Fblob\u002Fmain\u002Fpy-src\u002Fdata_formulator\u002Fanalyst\u002Fskills\u002Fcore\u002FSKILL.md",[115,116],{"categoryNo":72,"categoryName":73,"taxonomyType":27,"taxonomyTypeDesc":28},{"categoryNo":75,"categoryName":76,"taxonomyType":22,"taxonomyTypeDesc":23},[109,79,118],"python",{"skillNo":120,"name":121,"nameZh":122,"description":123,"descriptionZh":123,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":124,"categories":125,"keywords":130,"publishedAt":33},"01M69BFAS2GHW4CCQJR1PAXZPD","path-safety","服务端路径安全规范","服务端路径安全与文件访问编码规范。在编写文件下载路由、Agent 工具（文件读取\u002F目录列出）、数据连接器\u002FLoader、Workspace 路径操作、沙箱配置时使用。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdata-formulator\u002Fblob\u002Fmain\u002F.cursor\u002Fskills\u002Fpath-safety\u002FSKILL.md",[126,127],{"categoryNo":20,"categoryName":21,"taxonomyType":22,"taxonomyTypeDesc":23},{"categoryNo":128,"categoryName":129,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8BXREJNJE7HY785DVVKG7CW","Web应用安全防护",[131],"path safety",{"skillNo":133,"name":134,"nameZh":135,"description":136,"descriptionZh":136,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":137,"categories":138,"keywords":145,"publishedAt":33},"01M69BF8TAXKYRA9J8HY978H0H","language-injection","LLM Agent多语言注入规范","LLM Agent 多语言注入规范。在修改 Agent 提示词、添加新的 Agent 端点、处理用户可见的后端消息（message_code）时使用。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fdata-formulator\u002Fblob\u002Fmain\u002F.cursor\u002Fskills\u002Flanguage-injection\u002FSKILL.md",[139,142],{"categoryNo":140,"categoryName":141,"taxonomyType":22,"taxonomyTypeDesc":23},"01M8BRZZF9D7PVFN5MXSPWWD61","AI 工程师",{"categoryNo":143,"categoryName":144,"taxonomyType":27,"taxonomyTypeDesc":28},"01M8BSAA4FBTWZP6X98STEHG99","智能体开发",[146,147],"language injection","code"]