简体   繁体   中英

Mongodb Error codes and corresponding http status code

So, if a new user tries to sign up with an user account that already exists, MongoDb responds with a 11000 error code

In Express, that can be handled like this:

async function signup(req, res, next){
  try{ 
  // some stuff
  }catch(err){
    if (err.code === 11000) {
      err.message = 'Email is already taken.';
      res.statusCode = 409;
    }
    return next(err);
  }     
}

For this example, I decided to respond with a 409 http status code.

However, I am not sure if it's a good approach to handle several different codes from MongoDB and assigning an http status for each of them.

What other solutions am I missing?

You can return specific responses to common errors that you might come across.

But it really comes down to how specific you want to be. You also need to consider is it really worth it to customize the response for each and every single error that can occur. Some of them might never happen depending on your configuration.

For example, ncompatibleShardingConfigVersion will never happen if you are not using a sharded cluster.

Furthermore, if the error message is supposed to be displayed at the frontend, the users don't really care about the what, why, and how of an error. What he/she knows is that it doesn't work and he/she is not happy.

You have several options:

  1. Using conditionals like what you are doing now. Perhaps create a custom error constructor and put the conditionals in it to avoid having to repeat yourself in every single function call.

  2. Send a generic error message to the frontend with status code 500. Log the whole error object at the backend so you can know what went wrong. You are the person who actually cares about the why, what, how, when of an error.

Personally, I will go with option 2.

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