在蓝鸟中处理异常
Handling exception in Bluebird
function ApiError(response) {
this.message = 'API error';
this.response = response;
}
ApiError.prototype = Object.create(Error.prototype);
ApiError.prototype.constructor = ApiError;
ApiError.prototype.name = 'ApiError';
export default ApiError;
我有这个自定义异常,我会在某个时候抛出它,但是当我试图在承诺中捕获它时,例如
import ApiError from './ApiError';
...
.catch(ApiError, (e) => {
console.log('api error');
})
.catch((e) => {
console.log(e); <= this is undefined(in ApiError)
});
错误被委托给通用捕获,错误说消息无法分配给未定义( this=undefined
在 ApiError 中(,我在这里做错了什么?
编辑:问题实际上是我没有返回蓝鸟承诺的实例,而是节点Promise
(使用fetch
(,我通过将获取包装在蓝鸟Promise.resolve
中来解决它。
该错误听起来像您没有正确创建ApiError
对象的实例。
当你抛出一个错误时,它应该是:
throw new ApiError(xxx);
请注意,必须使用的new
。 错误的细节使其看起来像您没有使用new
。
或者,您可以更改 ApiError
构造函数的实现,以便您可以这样做;
throw ApiError(xxx);
但是,您必须更改 ApiError 以检测它是否使用 new
调用,如果没有,则调用new
本身。
function ApiError(response) {
if (!(this instanceof ApiError)) {
return new ApiError(response);
}
this.message = 'API error';
this.response = response;
}
或者,在 ES6 中,您可以使用new.target
选项:
function ApiError(response) {
if (!new.target) {
return new ApiError(response);
}
this.message = 'API error';
this.response = response;
}
问题实际上是我没有返回 Bluebird promise 的实例,而是 ES6 Promise(使用 fetch(,我通过将 fetch 包装在 Bluebird Promise.resolve 中来解决它。
相关文章:
- node.js和express中的异常处理
- JavaScript 异常处理未按预期工作
- tomcat服务器停止时UI上的异常处理
- 带异常处理的基数转换
- Javascript getJson异常处理
- 使用生成器进行异常处理
- 如何在保留 JavaScript 调试器功能的同时进行优雅的异常处理
- 了解 JavaScript 中的异常处理:当更改 try/catch 块的位置时,获得不同的输出
- 流星中的异常处理
- 角.如何在视图中显示异常处理程序的错误
- 如何使工作 Chrome 扩展程序的未捕获异常处理程序(由于 CORS 保护而不起作用)
- Selenium2/WebdriverJavaScript异常处理:错误消息大部分时间为空(Javaneneneba A
- 使用bluebird promise进行异步异常处理
- Vert-x 3.3.2 HTTP客户端异常处理程序
- Node.js最佳实践异常处理-异步/Await之后
- 异常处理程序不捕获异常
- NodeJS中的嵌套回调和异常处理
- React Native - `require()`语句异常处理
- 如何实现对importScripts()的异常处理
- 我想在Javascript/Jquery函数中使用异常处理