如何将反应错误发送到服务器并进行记录?

时间:2018-09-28 11:01:35

标签: node.js reactjs express error-handling

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

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

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
    }
})

//添加到错误的功能。向我发送有关错误的文字

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 Error Object像我在服务器上使用的一样格式不更改日志功能

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)
        })
    }

1 个答案:

答案 0 :(得分:0)

要像我发现的那样向服务器发送错误,您只有一个选择-分别发送error.stack和error.message,然后使用新的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 })
    })
}