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

时间:2018-07-26 11:48:39

标签: 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")类仅特定于一个错误。

我应该如何正确执行此操作?

1 个答案:

答案 0 :(得分:0)

您可以将以下标准用于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
}