简体   繁体   中英

Proper & Sustainable way of Error Handling in Node/Express API Routes

I've written a few MEAN Stack applications and set up API's but I've always had some level on confusion on whats the best way to handle errors inside an API Routes.

Please do correct me if I explained something wrong or my thinking/concept are flawed. I am explaining what I think is right. just trying to be a better programmer.

When I say errors I mean the following scenarios:

  1. A General error, something you did not predict has happened and needs to be handled, maybe the server is down or the server is overloaded, basically anything that we can't predict that might happen. This type of error mostly is handled here "I think" ( see comments below in code ):

     app.get('/user', isLoggedIn, function(req, res){ User.find(_id, function(err, user){ // HERE I am not sure how to handle this, Maybe we can't reach the DB or anything else could have happened. How do you handle this error so no matter what kind of error it is we can handle it gracefully and the app doesnt crash and we don't lose value data and the user is made aware of the issue. if(err) 

I have seen different ways how people have managed the above error here are a few examples:

if(err)
    // I think this is wrong! Maybe okay for development but not for deployment
    console.log("The Error is " + err);

if(err)
    // Again I think not a good way of handling error because doesn't provide the system or the front-end user with any useful data. 
    throw err;

if(err)
    // Not Sure
    res.send(err);

if(err)
    res.json(err);

So the above was when we can't predict what kind or when error might occurs but there also another type see below

  1. So lets says we passed the above if(err) stage and went to the else , this is where we CAN predict the errors because this is where User interaction comes into play. For example continuing the example above ( see comments in code ):

     app.get('/user',isLoggedIn,function(req, res) { User.find(_id, function(err, user) { if (err){ // NOT SURE WHAT TO DO HERE } // HERE lets say the user we are trying to get does not exist, now this is something we can predict, how to handle this not only gracefully so we don't crash the app but also provide the front end user with some useful information. else if(!user){ } else if(user){//Do what you were meant to do!} }); }) 

Now how I usually manage this type of error is by sending back some information to the front-end user like so:

return(res.json({message: "The user you are trying to find does not exist, contact the system admin please."}));

I send back some JSON data and display on the front end inside a div or an alert box etc.

So these are the two "kinds" or a better word "situations" of errors I deal with. Whats the best way of dealing with them so they the app can manage itself without crashing but also making sure the front-end user knows whats going on so they know their next step. And what are the best practices for handling errors in API's.

I prefer use next and custom Error

Next

app.get('/user', isLoggedIn, function(req, res, next){
    User.find(_id, function(err, user){
        if (err)
            return next(err); // Forwarding error to error-middleware
            ...or... 
            throw new Error('Cause'); // If error is critical for app and app must be stopped
        ...
    });

In Error-middleware we can choose how much info send to console/user and how present info

// Detect current environment
if (req.app.get('env') != 'development') {
    ...    
}

// Detect request type
if (req.xhr)
    req.json(...)
else
    res.render('error.html', ...);

Custom Error

In example above you can throw AuthorizeError and forwarding it by next . More about custom error read here . Imho it's excessively for small application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM