如何处理来自 Node.js 中 API 的 HTTPs json 格式错误?

维克多·莫利纳

介绍

我正在实现一个功能,用于向任何端点发出任何类型的 https 请求(使用 https 本机模块)。当我向特定 API 发出请求时,我收到JSON 格式错误响应像这样:

{
    "error": {
        "code": 404,
        "message": "ID not found"
     }
}

我该如何处理此类错误?一开始,我以为他们是在处理

request.on("error", (err) => { reject(err); });

HTTPS 请求函数代码

我在代码的相关部分有注释 '<---------'

const https = require("https");

exports.httpsRequest = function (options, body = null) {
  /* 
    This function is useful for making requests over the HTTPs protocol 
   */

  return new Promise((resolve, reject) => {
    const request = https.request(options, (response) => {
      // Get the response content type
      const contentType =
        response.headers["content-type"] &&
        response.headers["content-type"].split(";")[0];

      // Cumulate data
      let chuncks = [];
      response.on("data", (chunck) => {
        chuncks.push(chunck);
      });

      response.on("end", () => {
        // Concat all received chunks
        let response = Buffer.concat(chuncks);

        // Some responses might be in JSON format...
        if (contentType === "application/json") {
          // Jsonify the response
          response = JSON.parse(response);
        }

        // (For the future) TODO - Check and parse more content types if needed.

        // Resolve the promise with the HTTPs response
        resolve(response); // <--------- The JSON format error responses are resolved too!!
      });
    });

    // Reject on request error
    request.on("error", (err) => {
      // <------------- At a first moment, I supposed that all error responses were handled in this part of the code
      reject(err);
    });

    // Write the body
    if (body) {
      request.write(body);
    }

    // Close HTTPs connection.
    request.end();
  });
};

问题

为什么在 request.on("error", ...) 中没有处理错误响应?

谢谢你。我将不胜感激任何帮助或建议。

jfriend00

当内容类型不是您所期望的内容类型时,您需要创建一个不同的代码路径,reject()并且您还需要try/catch绕过 JSON 解析错误,以便您可以正确地捕获它们并拒绝它们。您可以使用以下代码解决这些问题:

exports.httpsRequest = function (options, body = null) {
  /* 
    This function is useful for making requests over the HTTPs protocol 
   */

  return new Promise((resolve, reject) => {
    const request = https.request(options, (response) => {
      // Get the response content type
      const contentType =
        response.headers["content-type"] &&
        response.headers["content-type"].split(";")[0];

      // Cumulate data
      let chuncks = [];
      response.on("data", (chunck) => {
        chuncks.push(chunck);
      });

      response.on("end", () => {
        // Concat all received chunks
        let response = Buffer.concat(chuncks);

        // Some responses might be in JSON format...
        if (contentType === "application/json") {
            try {
              // Jsonify the response
              response = JSON.parse(response);
              resolve(response);
              return;
            } catch(e) {
              reject(e);
              return;
            }
        }
        reject(new Error("Not JSON content-type"))
      });
    });

    // Reject on request error
    request.on("error", (err) => {
      reject(err);
    });

    // Write the body
    if (body) {
      request.write(body);
    }

    // Close HTTPs connection.
    request.end();
  });
};

仅供参考,此处got()列出的和其他都会自动为您完成这项工作,并具有许多其他有用的功能。你真的不需要自己构建这个。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Node.js中写入格式化的JSON

如何处理Dropbox Java API中的错误

如何处理Node.js中的循环依赖关系

如何在API中处理格式错误的请求

向Node.js中的JSON API发出GET请求?

如何处理Express Node.js中的主体解析器错误

如何处理Node.js中的fs.createReadStream()错误?

使用node.js测试API如何处理无效的JSON语法请求主体

如何处理异步/等待获取API中的错误404

如何处理Node.js / express中的错误

如何在node.js(openweathermap.api)中呈现html格式

如何处理Node.js中的异步错误

修改从Node.js中的API检索的JSON数据

如何处理Node.JS中的UnhandledPromiseRejectionWarning

Next.JS:如何处理getInitialProps中的错误?

如何在整个api调用中使用node.js中的全局错误处理代码

使用https的Node.js中的套接字挂起错误

我应该如何处理Ember.js中来自服务器的错误?

AngularJS从Node.js API中获取JSON

在node.js中初始化|| 如何处理node.js中的初始配置

如何处理来自node.js的网页上的数据

我如何解析来自node.js中的facebook graph api的json响应

如何处理 node.js 请求中的 URI 错误?

如何在Node js中从json格式拆分字符串

如何处理来自 Rails 中 gems 的网络请求的渲染 json 错误?

在 RxSwift 中解析 JSON 并处理来自 API 的错误响应

json_encode($response); 如何处理 Json API,用 Laravel 提取 json 格式

如何处理 Rails API 中的一般错误?

如何处理来自 API 请求抖动的错误