javascript - 如果 statusCode 不是 200,http 调用会返回什么类型的错误对象?

标签 javascript node.js api meteor error-handling

我正在使用 npm 'request' 包在 Meteor 中进行 http 调用。

我想知道当response.statusCode不等于200时会创建什么类型的错误对象?这是否由 JavaScript 引擎处理并被视为运行时错误

或者如果statusCode不等于200,由服务提供商决定是否创建错误对象?

如果是后者,我是否创建一个“手动错误”,new Error('抛出我自己的错误以供 catch block 处理')

var request = function() {
// HTTP call to server
  },  
  function (error, response, body) {    
  if (!error && response.statusCode === 200) {
    // processed and created data object
      return data
  }
  else {
     return (error) ; // How can I ensure the catch(e) block in the try/catch method will catch the error with an addition of my own 'message'. 
  }
})
};

try {
    request()
}
catch(e) {
  console.log(e)
}

对于我的场景,我想确保 catch(e) block 能够捕获此错误,并且我想添加我自己的消息,包括堆栈跟踪。

最佳答案

您不必使用try..catch除非操作使用同步代码(例如使用 Meteor http 包使用 http.get 发出请求)。

错误码一般是对方服务器返回的。 200表示还可以。有一个huge list of potential错误代码及其含义。

因此error中的回调会返回状态码对象但不会被 catch 捕获除非使用 throw 抛出它就像你提到的。

在 javascript 中,问题是当存在带有错误参数的回调时,它实际上不会抛出可以从触发原始函数的位置(您拥有的 request() 方法)捕获的错误(如果这是有意义的)。

即使您使用 throw 在回调中它不会被 catch 捕获。这是因为回调是作为一个全新的事件触发的。如果您想使用catch你需要同步 javascript 技术。即使用 http 包。

meteor add http

然后是代码:

try {
    var result = HTTP.get("<url>")
    result.content //this will contain the response
}catch(e) {
    the `e` object will contain the error (if the status code is not 200)
}

您可以通过将自己的错误放入 catch(e) {...} 来更改错误 block 即

...
catch(e) {
    throw new Meteor.Error(500, "Internal Server Error");
}
...

您可以抛出 new Errornew Meteor.Error 。不同之处在于 Meteor.Error 也会将错误作为 err 的一部分发送到客户端。如果这段代码正在客户端使用 Meteor.call 调用的方法中运行,则回调例如

Meteor.call("something", function(err, result) {
    if(err) alert(err.reason);
});

如果调用这样的方法:

Meteor.methods({
    something: function() {
        throw new Meteor.Error(500, "This is the message");
    }
});

客户端将显示一个消息框,显示 This is the message作为err.reason 。如果你抛出new Error(..它不会将消息发送到客户端,而是将消息 Internal Server Error而不是This is the message

在该方法中,您可以拥有请求 url 的代码。如果它在其中抛出错误,它将在堆栈中冒泡并找到到达客户端的方式。

关于javascript - 如果 statusCode 不是 200,http 调用会返回什么类型的错误对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28782478/

相关文章:

python - 使用 Elsevier Scopus API 获取论文引用

javascript - 如何在回调中访问正确的“this”?

javascript - Bootstrap 日期选择器格式不适用于初始化

node.js - adonis/node.js 中不存在关系

windows - 如何在 node.js 和 Windows 之上安装和运行 lessc?

javascript - 在 Javascript Web 应用程序中保护私有(private) API key

java - Twilio sdk 不对应 api

javascript - 使用 javascript 通过数据库附加链接

javascript - 始终显示丹麦时间的 moment.js 时钟

css - 使用 Node.js 和 Express 时,路由参数导致 CSS 无法加载