我想知道处理响应中的错误的最佳方法-请求。
我有一条收到请求的路线:

app.get('/getInfo', function (req, res, next) {
    let obj = {}
    try {
        obj = {
            ...
            date: lastUpdatedDate('./utils/appVersion.js'),
            ...
        }
        res.status(200).send(obj)
    } catch (error) {
        console.log(error.message)
        res.send({error: "The data wasn't load"})
    }
})

以及发出请求的功能
getInfo () {
    axios.get(process.env.REACT_APP_HOST + '/getInfo')
      .then(resp => {
        this.appInfoHandler(resp.data)
      })
      .catch(function (error) {
        console.log(error)
      })
  }

如果错误发生在服务器端,最好的解决方法是什么?
让我们假设在此代码块中目录不存在:lastUpdatedDate('./directoreyDoesntExists/appVersion.js'),
所以我的代码转到了catch块。

我应该这样发送错误:
res.send({error: "The data wasn't load"})

我应该设置这样的状态吗?
  res.status(500).send({error: "The data wasn't load"})

还是应该使用其他状态代码设置状态?

基于此,在前端方法getInfo()中获取错误并在Web界面上显示错误消息的最佳方法是什么?

我应该这样在if else块内执行.then吗?
 getInfo () {
      axios.get(process.env.REACT_APP_HOST + '/getInfo')
      .then(resp => {
            if(resp.status === 200){
                 this.appInfoHandler(resp.data)
            }else if (resp.status === 400){
                  //print error message on web interface
            }else if (resp.status === 500){
                  //print error message on web interface
          })
          .catch(function (error) {
            console.log(error)
          })

还是我应该像这样直接在catch块中处理此错误
getInfo () {
    axios.get(process.env.REACT_APP_HOST + '/getInfo')
      .then(resp => {
        this.appInfoHandler(resp.data)
      })
      .catch(function (error) {
        //print error message on web interface
      })
  }

最佳答案

200以外的任何状态代码均表示不成功,因此您无需使用这些if-else语句。更好的选择是捕获错误并按原样发送并发送响应。这样做的好处是,您无需对状态代码进行硬编码就可以收到发生的错误类型。
(例如,我们将此处的状态代码设为400不成功)

 .catch(function (error) {
        //print error message on web interface
        res.status(400).send(JSON.stringify(error, undefined, 2));
      });

通过使用stringify方法,您还可以在控制台上打印确切的错误。
.catch(function (error) {
            console.log(JSON.stringify(error, undefined, 2));
          });

这里的stringify方法中的参数是:
  • 错误对象
  • 未定义:包含用于过滤对象中键的键的数组(此处为error)。该数组中存在的所有那些键只是未被过滤掉的那些键。
  • 2:用于在对象表示形式
  • 中引入空格

    09-10 02:04
    查看更多