admin管理员组

文章数量:1323347

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

And this function where the request is made

getInfo () {
    axios.get(process.env.REACT_APP_HOST + '/getInfo')
      .then(resp => {
        this.appInfoHandler(resp.data)
      })
      .catch(function (error) {    
        console.log(error)
      })
  }

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

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?

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?

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

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

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

And this function where the request is made

getInfo () {
    axios.get(process.env.REACT_APP_HOST + '/getInfo')
      .then(resp => {
        this.appInfoHandler(resp.data)
      })
      .catch(function (error) {    
        console.log(error)
      })
  }

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

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?

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?

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

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
      })
  }
Share Improve this question edited Jun 26, 2019 at 12:34 mr.abdo asked Jun 26, 2019 at 12:22 mr.abdomr.abdo 4851 gold badge6 silver badges17 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

For this case

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

vs

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

send a status is just more detailed, but both are ok. check Proper way to set response status and JSON content

For this case, depends on what you need

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

vs

getInfo () {
    axios.get(process.env.REACT_APP_HOST + '/getInfo')
      .then(resp => {
        this.appInfoHandler(resp.data)
      })
      .catch(function (error) {    
        //print error message on web interface
      })
  }

You can handle all the errors sending them to the catch block

else if (resp.status === 400){
                  //print error message on web interface

not printing the error in here but throwing a new error that will be send it to the catch block

throw new ApiError("UserNotFount",400,"not found");
throw new Error('Error 400, not found');

For this case

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

vs

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

I would suggest sending error as well as status code because that will be more descriptive for the client.

and for the second case

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

vs

getInfo () {
    axios.get(process.env.REACT_APP_HOST + '/getInfo')
      .then(resp => {
        this.appInfoHandler(resp.data)
      })
      .catch(function (error) {    
        //print error message on web interface
      })
  }

In this case I would suggest to use the catch block directly whenever you get an error because response status depends on error but not the other way around

As a beginner working on a REST Api, you should take a look at a guidelines - microsoft's are pretty legit: https://learn.microsoft./en-us/azure/architecture/best-practices/api-design.

Basically, you need to return the correct HTTP code for each request, take a look at https://http.cat/ - for example if the request is malformed, return 400, and if the user is unauthorized return 401:

if (!req.body.name) {
  res.status(400).send({ error: 'missing user name' }); // 400 bad request
}
const user = getUser(req.body.name, req.body.pass);

if(!user) {
  res.status(401).send({ error: 'user does not exist' }); // 401 unauthorized
}

try {
  const token = createToken(user);
  // better to set a cookie
  res.status(200).send({ token }); // 200 success
} catch(e) {
  res.status(500).send({ erroe: e.message }); // 500 internal error
}

if(isTeapot) {
  res.status(418).send({ error: 'I can only make tea' }); // 418 teapot, totally real
}

To make things easier there are a lot of libraries to help you generate better error messages and handle errors better, one of my favorites is celebrate

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

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

The parameters in the stringify method here are:

  1. error object

  2. 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.

  3. 2: It is used to introduce whitespace in object representation

本文标签: