【发布时间】:2015-08-12 11:14:01
【问题描述】:
我有一个包装 AJAX 请求的 Bluebird 承诺,并且需要在请求失败时拒绝该承诺。我想提供请求失败的原因,主要来自状态代码,可能附加的任何捕获块。为了实现这一点,我有 UnauthorizedError 和 NotFoundError 以及类似的类,它们都扩展了 Error 以使用 Bluebird 的模式匹配 catch。
我不确定的部分是我应该throw 还是调用拒绝处理程序。我的代码看起来像:
class Request {
// other methods
send(method, url, args, body) {
return new Promise((res, rej) => {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = () => {
res(JSON.parse(xhr.responseText));
};
xhr.onerror = () => {
let status = xhr.status;
switch (status) {
case 401:
// Should I use throw:
throw new UnauthorizedError(url);
// or
rej(new UnauthorizedError(url));
}
};
xhr.send();
});
}
}
【问题讨论】:
标签: javascript error-handling promise ecmascript-6 bluebird