Next.js-堆栈驱动程序错误报告-不记录错误



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

使用此库:https://github.com/GoogleCloudPlatform/stackdriver-errors-js

App.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)
}
}
}
}, [])

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

谢谢!

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

//抄送@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

最新更新