gpt4 book ai didi

node.js - 如何将 react 错误发送到服务器并记录它?

转载 作者:太空宇宙 更新时间:2023-11-03 22:22:30 25 4
gpt4 key购买 nike

我正在尝试将 React ErrorBoundary 捕获的 react 错误或我自己创建的错误发送到服务器并记录它们,但不知道如何正确且简单地做到这一点。

在我的 Express 服务器上,我在这样的文件中记录错误(并且它正在工作 ^_^):

app.get('/readers/:id', async (req, res, next) => {
try {
//do something
} catch (err) {
next(myError(err, 'error in app.get(/readers/:id)')) //add my message to error.message and let express handle it at the bottom bloc of code
}
})

//将有关错误的文本添加到 error.message 的函数

function myError(err, myMessage) {
err.message = myMessage + '\r\n' + err.message
return err
}

//处理所有明确的错误

app.use(async (err, req, res, next) => {
try {
logError(err) //log error to file
res.status(500).send('something wrong')
} catch (err) {
return console.log('error when logging: ' + err)
}
})

//将任何错误记录到文件

async function logError(err) {
fs.appendFile('./logs/error_log.txt', new Date() + '\r\n' + err.message + '\r\n' + err.stack + '\r\n\n', (e) => {
if (e) console.log('error when logging ' + e.message + '\r\n\n' + e.stack)

console.log('error logged ')
});
}

现在问题出在哪里。我们有 ErrorBoundary 来捕获错误并给我错误对象,它只是一条关于错误的消息和关于错误发生的位置和状态的堆栈信息。

export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props)
this.state = { hasError: false }
}

componentDidCatch(error, info) {

this.setState({ hasError: true })
sendErrorToExpressAndlogThere(error, info)
}



render() {
if (this.state.hasError) {
//render some error for user
}
return this.props.children
}
}

如何将信息堆栈添加到我不明白的错误对象

我尝试使用 JSON.stringify(info) 将堆栈添加到 error.message 像字符串一样但我只得到第一行而不是堆栈跟踪

enter image description here

我也不明白如何使 react 错误对象与我在服务器上使用的格式相同而不更改日志功能

sendErrorToExpressAndlogThere(error, info) {
error.message += ' Error in react boundary ' + info;

fetch('/errorlog', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
error: JSON.stringify(body)
})
}

最佳答案

为了能够像我发现的那样向服务器发送错误,您只有一个选择 - 分别发送 error.stack 和 error.message,然后使用 new Error() 将其记录在服务器上。

componentDidCatch(error, info) {
this.reactError = error
console.log(info)
this.setState({ catchError: true })
}


sendError() {
fetch('/errorlog', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({ message: this.props.type + ' - ' + this.props.error.message, stack: this.props.error.stack })
})
}

关于node.js - 如何将 react 错误发送到服务器并记录它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52553933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com