node.js - Node.js如何正确引发错误?

标签 node.js rest api error-handling

给出的选项是好的做法还是需要改进?
如果那样的话,你能告诉我如何吗?

// Situation 1 - developer error
error: {
  name: "Unauthorized",
  message: "Authentication token was not found / incorrect",
  code: "401"
}

// Situation 2 - user's faults
error: {
  name: "Bad Request",
  message: {
    first_name: "Please fill first name 2-10 chars long",
    last_name: "Last name is not allowed to contain digits - letters only"
  },
  code: "400"
}

// Situation 3 - everything is okay.
data: {
  user: {
    first_name: "John",
    last_name: "Doe"
  },
  code: "200"
}

基本上,我想返回多个错误或描述性错误,但是new Error("error")类仅特定于一个错误。

我应该如何正确地做到这一点?

最佳答案

您可以对REST API响应使用以下标准。

**Success Response:**
    {
     "code": 200,
     "success": true,
     "data": {},
     "message": "Vendor created successfully."
    }

**Internal Server Error Response:**
        {
           code: 500,
            success: false,
            message: "Internal Server Error",
            error: err
        }

**Process Error Response:**

        {
            success: false,
            message: msg,
            data:{},
            code: 409,
            process_code: process_code
        };

**Fields Validation Error Response:**

       {
            errors: errors,
            code: 400,
            success: false,
            message: "Fields validation failed."
        }


**404 Resource Not Found Response:**

{
    "code": 404,
    "success": false,
    "message": "Resource Not Found.",
    "error":err
}

关于node.js - Node.js如何正确引发错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51538126/

相关文章:

node.js - 带有node.js的mongodb中的地理空间索引

node.js - 套接字断开连接上的 Socket.io

rest - 真正的 RESTful 服务实例

python - Python Django-REST-framework 和 Angularjs 的文件夹结构

php - 如何在 header php 中使用 api token

node.js - Loopback HasManyThrough 关系仅以一种方式工作

javascript - Open Shift中如何修改 Node 启动命令?

xml - 400 对剩余应用程序/xml 的错误请求

javascript - 更新子文档 Mongoose 中的字段

c# - 是否可以在使用 SalesForce Soap API 插入之前向自定义对象添加附件?