使用nodejs + express处理服务器端和客户端错误的最佳方法是什么 [英] What's the best way to deal with an error in the server side and in the client side using nodejs + express

查看:171
本文介绍了使用nodejs + express处理服务器端和客户端错误的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to know the best way to deal with errors in a response - request. I have this route that receive a request:

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'),

What's the best way to deal with the error if it occurs in the server side? Let's supose that in this code block the directory doesn't exists: lastUpdatedDate('./directoreyDoesntExists/appVersion.js'),

所以我的代码转到了catch块.

So my code goes to the catch block.

我应该发送这样的错误:

Should I send the error like this:

res.send({error: "The data wasn't load"})

我应该设置这样的状态吗?

Should I set a status like this?

  res.status(500).send({error: "The data wasn't load"})

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

Or should I set a status with a different status code?

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

Based on that, what's the best way to deal with it in my frontend method getInfo() to get the error and show the error message on web interface?

我应该像这样在.then块内做一个if else吗?

Should I do an if else inside the .then block like this?

 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块中像这样处理该错误

Or should I deal with this error directly in the catch block like this

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不成功)

Any status code other that 200 would mean unsuccessful so you dont need to use those if-else statements. The better alternative is to catch the error and send it with response as it is. The benefit is that you would receive the type of error occured without hardcoding the status codes. (for ex, we take the status code here to be 400 unsuccessful)

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

通过使用stringify方法,您还可以在控制台上打印确切的错误.

By using the stringify method you can print the exact error on the console also.

.catch(function (error) {    
            console.log(JSON.stringify(error, undefined, 2));
          });

这里的stringify方法中的参数是:

The parameters in the stringify method here are:

  1. 错误对象

  1. error object

未定义:包含用于过滤对象中键的键的数组(此处为error).该数组中存在的所有那些键只是未被过滤掉的那些键.

undefined: The array which contains the keys for filtering the keys in the object(here, error). All those keys present in this array are only the ones not filtered out.

2:用于在对象表示中引入空格

2: It is used to introduce whitespace in object representation

这篇关于使用nodejs + express处理服务器端和客户端错误的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆