> ## Documentation Index
> Fetch the complete documentation index at: https://docs.devin.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 自动分流 Sentry 错误

export const UseCaseHero = ({title, description, prompt, category, features, devinUrl, agent, intent, playbookId, type}) => {
  const encodedPrompt = encodeURIComponent(prompt || '');
  const tag = 'docs-use-case-gallery';
  const utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=hero-cta';
  const agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  const devinHref = type === 'schedule' ? 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + (prompt ? '&prompt=' + encodedPrompt : '') : type === 'review' ? 'https://app.devin.ai/review?' + utm : agent === 'ada' ? 'https://app.devin.ai/search?' + utm + '&noSubmit=true' + (prompt ? '&prompt=' + encodedPrompt : '') : devinUrl ? devinUrl.includes('?') ? devinUrl + '&' + utm + agentParams : devinUrl + '?' + utm + agentParams : prompt ? 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encodedPrompt : 'https://app.devin.ai/?' + utm + agentParams;
  const buttonLabel = type === 'schedule' ? 'Schedule in Devin ↗' : type === 'review' ? 'Set Up Devin Review ↗' : agent === 'advanced' ? 'Try in Devin ↗' : agent === 'dana' ? 'Try in Dana ↗' : agent === 'ada' ? 'Try in Ask Devin ↗' : 'Try in Devin ↗';
  const featureList = features ? features.split(',').map(f => f.trim()) : [];
  return <div className="uc-hero">
      <div className="uc-hero-inner">
        <div className="uc-hero-left">
          <h1 className="uc-hero-title">{title}</h1>
          <p className="uc-hero-desc">{description}</p>
          <div>
            <a href={devinHref} target="_blank" rel="noopener noreferrer" className="try-in-devin-btn">
              {buttonLabel}
            </a>
          </div>
        </div>
        <div className="uc-hero-meta">
          <div className="uc-meta-item">
            <span className="uc-meta-label">Author</span>
            <span className="uc-meta-value">Cognition</span>
          </div>
          <div className="uc-meta-item">
            <span className="uc-meta-label">Category</span>
            <span className="uc-meta-value">{category}</span>
          </div>
          {featureList.length > 0 && <div className="uc-meta-item">
              <span className="uc-meta-label">Features</span>
              <span className="uc-meta-value">{featureList.join(', ')}</span>
            </div>}
        </div>
      </div>
    </div>;
};

export const PromptBlock = ({children, type, agent, intent, playbookId}) => {
  var utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=prompt-block';
  var tag = 'docs-use-case-gallery';
  var agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  var label = type === 'schedule' ? 'Schedule in Devin' : type === 'playbook' ? 'Create Playbook' : type === 'knowledge' ? 'Add to Knowledge' : agent === 'advanced' ? 'Try in Devin' : agent === 'dana' ? 'Try in Dana' : agent === 'ada' ? 'Try in Ask Devin' : 'Try in Devin';
  var buildUrl = function (text) {
    var encoded = encodeURIComponent(text);
    if (type === 'schedule') return 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + '&prompt=' + encoded;
    if (type === 'playbook') return 'https://app.devin.ai/settings/playbooks/create?' + utm + '&body=' + encoded;
    if (type === 'knowledge') return 'https://app.devin.ai/knowledge?' + utm + '&body=' + encoded;
    if (agent === 'ada') return 'https://app.devin.ai/search?' + utm + '&noSubmit=true&prompt=' + encoded;
    return 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encoded;
  };
  const ref = React.useRef(null);
  const [href, setHref] = React.useState('#');
  React.useEffect(() => {
    if (!ref.current) return;
    var codeEl = ref.current.querySelector('pre code');
    if (codeEl) {
      var text = codeEl.textContent.trim();
      if (text) setHref(buildUrl(text));
    }
    var header = ref.current.querySelector('[data-component-part="code-block-header"]');
    if (header && !header.querySelector('.prompt-block-devin-link')) {
      var link = document.createElement('a');
      link.href = href;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.className = 'prompt-block-devin-link';
      link.style.cssText = 'display:inline-flex;align-items:center;gap:6px;text-decoration:none;color:#fff;font-size:11px;font-weight:500;padding:4px 10px;border-radius:6px;white-space:nowrap;background:#317CFF;transition:background 0.2s;margin-left:8px;';
      link.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg> ' + label;
      link.onmouseenter = function () {
        link.style.background = '#2968D9';
      };
      link.onmouseleave = function () {
        link.style.background = '#317CFF';
      };
      header.appendChild(link);
    }
    var existingLink = ref.current.querySelector('.prompt-block-devin-link');
    if (existingLink && href !== '#') existingLink.href = href;
  });
  return <div className="prompt-block" ref={ref}>{children}</div>;
};

<UseCaseHero title="自动分级处理 Sentry 错误" description="将 Sentry webhook 接入 Devin API，以自动分级处理每个新的生产环境错误。" prompt="帮我搭建一个从 Sentry 到 Devin 的自动分级处理流水线。请按照 https://docs.devin.ai/use-cases/gallery/api-sentry-auto-triage 中的指南，引导我完成每一步：启用 Sentry MCP、创建内部集成，以及部署 webhook 处理程序。" category="事件响应" features="API, MCP" />

<div className="uc-detail-wrapper">
  <Tip>如需更详细的 Sentry 集成指南，请[点击此处](/zh/enterprise/integrations/sentry)。</Tip>

  <Steps>
    <Step title="启用 Sentry MCP">
      Devin 需要访问你的 Sentry 账户，以便在问题分诊时获取堆栈跟踪、breadcrumbs 和事件元数据。

      1. 前往 **Settings > Connections > MCP 服务器** 并找到 **Sentry**
      2. 点击 **Enable**，使用有权访问你项目的 Sentry 账户完成 OAuth 流程
      3. 测试连接 —— 启动一个会话，让 Devin 列出你某个项目中的最近问题

      连接后，Devin 可以查询你的账户有权访问的任意 Sentry 项目：问题详情、完整堆栈跟踪、事件 breadcrumbs、发布 (release) 标签等。有关详细设置步骤，请参见 [MCP Marketplace 文档](/zh/work-with-devin/mcp)。
    </Step>

    <Step title="创建 Sentry 内部集成">
      Sentry 通过 Internal Integrations 发送 webhooks。在你的 Sentry 仪表盘中，前往 **Settings > Developer Settings > Custom Integrations**，然后点击 **Create New Integration > Internal Integration**。

      按如下方式进行配置：

      * **Name：** `Devin Auto-Triage`
      * **Webhook URL：** 你将在下一步部署的服务 (例如：`https://your-domain.com/sentry-webhook`)
      * **Alert Rule Action：** 将其切换为 **On** —— 这会让该集成在告警规则中可作为一个动作使用
      * **Permissions：** 对 **Issue & Event** 和 **Project** 的只读访问权限

      保存该集成，然后创建一个告警规则。在你的项目前往 **Alerts > Create Alert Rule > Issue Alert**：

      * **When：** 当创建了一个新的 Issue 时
      * **If：** 该 Issue 在 **1 hour** 内有超过 **50** 个事件 (可根据你的流量进行调整)
      * **Then：** 通过 **Devin Auto-Triage** 发送通知
    </Step>

    <Step title="将该 webhook 接入 Devin API">
      构建一个轻量级处理程序，用于接收 Sentry 的告警负载并启动 Devin 会话。在 **Settings > Service Users** 中创建一个具有 `ManageOrgSessions` 权限的 [service user](/zh/api-reference/v3/overview)，并将其令牌在处理程序的环境中保存为 `DEVIN_API_KEY`。将 `DEVIN_ORG_ID` 设置为你的组织 ID——可通过使用该令牌调用 `GET https://api.devin.ai/v3/enterprise/organizations` 获取。

      ```javascript theme={null}
      const express = require('express');
      const app = express();
      app.use(express.json());

      app.post('/sentry-webhook', async (req, res) => {
        const event = req.body.data?.event;
        if (!event) return res.sendStatus(200);

        const orgId = process.env.DEVIN_ORG_ID;
        const response = await fetch(
          `https://api.devin.ai/v3/organizations/${orgId}/sessions`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${process.env.DEVIN_API_KEY}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            prompt: [
              `A Sentry alert fired for a new issue: "${event.title}"`,
              `Culprit: ${event.culprit}`,
              `Sentry URL: ${event.web_url}`,
              ``,
              `Use the Sentry MCP to pull the full stack trace and breadcrumbs.`,
              `Identify the root cause, fix the issue, and open a PR with a`,
              `regression test.`,
            ].join('\n'),
            tags: ['sentry-auto-triage', `project:${event.project}`],
          }),
        });

        const { session_id } = await response.json();
        console.log(`Started Devin session ${session_id} for: ${event.title}`);
        res.sendStatus(200);
      });

      app.listen(3000);
      ```

      将此部署在任何可以接收 HTTPS 流量的环境中——例如 Cloudflare Worker、AWS Lambda，或一台小型 VPS。然后将你的 Sentry Internal Integration 的 webhook URL 指向它。

      上述代码会为每个会话打上 `sentry-auto-triage` 标签以及 Sentry 项目名称。这样你就可以在 Devin 仪表盘中过滤这些会话，并通过 API 使用 `tags` 查询参数[获取这些会话](/zh/api-reference/v3/sessions/get-organizations-sessions)——这对于按项目追踪 Devin 为多少错误进行了自动分诊非常有用。

      要验证整个流程是否正常工作，可以在 Sentry 中触发一次测试告警 (或者临时降低阈值) ，然后在 [app.devin.ai](https://app.devin.ai/?utm_source=docs\&utm_medium=use-case-gallery) 中查看是否出现了一个带有 `sentry-auto-triage` 标签的新会话。
    </Step>

    <Step title="Devin 如何处理每条告警">
      当有新的错误超过你的阈值并触发 webhook 时，Devin 会启动一个会话并按以下步骤处理问题：

      1. **通过 MCP 查询 Sentry** —— 拉取完整堆栈跟踪、breadcrumbs (导致崩溃的用户操作记录) 、受影响的浏览器/操作系统/版本标签以及事件发生频率
      2. **追踪根本原因** —— 在堆栈跟踪指向的精确行读取源码文件，沿着数据流分析为何该值为 `undefined` 或 `null`
      3. **编写有针对性的修复** —— 实现错误处理 (可选链、默认值、输入校验) ，并与现有代码库的既有模式保持一致
      4. **添加回归测试** —— 创建一个测试用例来重现最初的崩溃场景，并验证该修复可以防止问题再次发生
      5. **创建一个 PR** —— 在 PR 描述中附上 Sentry 问题的 URL，方便评审者交叉引用原始错误上下文和事件量

      示例 PR 描述：

      ```
      Fix: TypeError in UserProfile when user.profile is null

      Root cause: The /api/users/:id endpoint returns { profile: null }
      for users who haven't completed onboarding. UserProfile.tsx:47
      destructures email from user.profile without a null check.

      Fix: Added optional chaining and a fallback state.
      Test: Added test for users with null profile — verifies the
      component renders "Complete your profile" instead of crashing.

      Sentry issue: FRONTEND-1892 (340 events in the past hour)
      ```
    </Step>

    <Step title="借助 playbooks 和 Knowledge 优化分诊流程">
      流程运行起来后，可以进一步提升自动分诊的智能程度：

      **创建分诊 playbook。** 从 [`!triage` 模板 playbook](https://app.devin.ai/settings/playbooks/14fed18b89d44713a26e673cf258f548?utm_source=docs\&utm_medium=use-case-gallery) 开始——复制一份，并根据你团队的错误处理约定 (如错误边界、空值检查模式、日志格式) 进行自定义。然后，在你的 webhook 处理程序中，向请求体添加 `"playbook_id": "your-playbook-id"` 来传递 playbook ID。你也可以让 Devin 根据你分诊工作流程的描述生成一个 playbook。

      **添加 [Knowledge](/zh/product-guides/knowledge)**，涵盖你的 API 合约和已知边界情况——例如，"`/api/users` 的响应对于尚未完成引导流程的用户可能返回 `{ profile: null }`。始终要对这种情况做好防护。" 让 Devin 基于你现有的文档帮助你编写 Knowledge 条目。Devin 掌握的领域上下文越多，修复结果就越准确。

      **谨慎限定告警作用域。** 使用 Sentry 的告警规则条件来限制哪些错误会触发 Devin——可按项目、环境 (仅 `production`) 或错误量进行筛选。一个不错的起点是：只对首小时内事件数超过 50 的问题触发，以便聚焦高影响错误。

      **设置每周回顾计划。** 创建一个每周运行一次的 [schedule](https://app.devin.ai/settings/schedules/create?utm_source=docs\&utm_medium=use-case-gallery)，用于回顾自动分诊会话的结果，并将经验反馈到你的 playbook 和 Knowledge 中：

      <PromptBlock type="schedule">
        ```txt 每周 Sentry 自动分诊回顾 theme={null}
        回顾过去一周内所有打上 "sentry-auto-triage" 标签的 Devin 会话。
        对每个会话检查：

        1. PR（pull request）结果 —— 是已合并、未合并即关闭，还是仍然打开？
        2. Sentry 问题状态 —— 是否被标记为已解决/已修复、已忽略或已驳回？
        3. 该 PR 上是否有任何审阅者评论或变更请求

        基于这些信号：
        - 如果 PR 经常被关闭，或收到相同类型的反馈（例如：“这里不要使用
          可选链式调用，请使用显式的条件保护”），则在 !sentry-triage
          playbook 中更新相应约定
        - 如果 Devin 因缺少上下文而产生了错误修复，在 Knowledge 中新增一条
          覆盖该领域的条目（例如 API 合约、服务依赖）
        - 汇总：本周共运行了多少次会话，有多少 PR 被合并 vs 被关闭，
          以及反馈中是否存在模式

        将这份汇总发送到 Slack 上的 #engineering-ops 频道。
        ```
      </PromptBlock>
    </Step>
  </Steps>
</div>
