【问题标题】:Next.js - Stack Driver error reporting - errors are not loggedNext.js - 堆栈驱动程序错误报告 - 不记录错误
【发布时间】:2022-08-14 20:53:00
【问题描述】:

我试图将 Next.js 应用程序中的错误记录到 Stack Driver 中。

有了这个库:https://github.com/GoogleCloudPlatform/stackdriver-errors-js

应用程序.tsx

useEffect(() => {
   TagManager.initialize({
     gtmId: process.env.NEXT_PUBLIC_GTM_ID as string,
   })

   if (process.env.NODE_ENV !== \'development\') {
     const errorHandler = new StackdriverErrorReporter()
     errorHandler.start({
       key: process.env.NEXT_PUBLIC_API_KEY || \'\',
       projectId: process.env.NEXT_PUBLIC_PROJECT_ID || \'\',
       service: \'service_id\',
       version: \'2\',
     })

     window.onerror = function (_msg, _file, _line, _col, error) {
       // callback is called with an Array[StackFrame]
       if (error) {
         errorHandler.report(error)
       }
     }
  }
}, [])

但是堆栈驱动程序中没有记录任何错误。有没有人遇到过这个问题? 在这种情况下,我会在那里发布我的下一次旅程。

谢谢!

  • 您在哪个 Google Cloud 服务上运行此代码?如果在 Compute Engine 上运行,该服务是否具有 IAM 角色和正确的范围?使用更多详细信息编辑您的问题。
  • 我的应用程序在 vercel.com 上运行。我只想使用 stackdriver 平台。我找到了nextjs.org/docs/advanced-features/…。我会让你知道进展情况。

标签: reactjs next.js stackdriver


【解决方案1】:

我通过使用自定义 ErrorBoundary 解决了这个问题并包装了整个_app.tsx:

//cc @John Handley

import React, { Component, ErrorInfo, ReactNode } from 'react'
import StackdriverErrorReporter from 'stackdriver-errors-js'

interface Props {
  children?: ReactNode
}

interface State {
  hasError: boolean
}

class AppErrorBoundary extends Component<Props, State> {
  public state: State = {
    hasError: false,
  }

  public static getDerivedStateFromError(_: Error): State {
    // Update state so the next render will show the fallback UI.
    return { hasError: true }
  }

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    const errorHandler = new StackdriverErrorReporter()
    errorHandler.start({
      key: process.env.NEXT_PUBLIC_API_KEY || '',
      projectId: process.env.NEXT_PUBLIC_PROJECT_ID || '',
      service: '',
      version: '2',
    })

    errorHandler.report(error)
    console.error('Uncaught error:', error, errorInfo)
  }

  public render() {
    if (this.state.hasError) {
      return <h1>Sorry.. there was an error</h1>
    }

    return this.props.children
  }
}

export default AppErrorBoundary

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 2011-03-03
    相关资源
    最近更新 更多