简体   繁体   English

Mongodb 错误代码和对应的 http 状态代码

[英]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因此,如果新用户尝试使用已存在的用户帐户进行注册,MongoDb 会返回11000 错误代码

In Express, that can be handled like this:在 Express 中,可以这样处理:

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.对于此示例,我决定使用 409 http 状态码进行响应。

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.但是,我不确定这是否是处理来自 MongoDB 的几个不同代码并为每个代码分配 http 状态的好方法。

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.例如,如果您不使用分片集群, ncompatibleShardingConfigVersion将永远不会发生。

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.也许创建一个自定义错误构造函数并将条件放入其中以避免在每个 function 调用中重复自己。

  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.向前端发送一条状态码为 500 的通用错误消息。在后端记录整个错误 object,以便您知道出了什么问题。 You are the person who actually cares about the why, what, how, when of an error.你是真正关心错误的原因、内容、方式、时间的人。

Personally, I will go with option 2.就个人而言,我将 go 与选项 2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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