I have a Bluebird promise that wraps an AJAX request and need to reject the promise when the request fails. I would like to provide the reason why the request failed, largely drawn from the status code, to any catch blocks that may be attached. To achieve that, I have UnauthorizedError
and NotFoundError
and similar classes, all extending Error
to work with Bluebird's pattern-matching catch
.
The part I'm not sure on is whether I should throw
or call the reject handler. My code looks something like:
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();
});
}
}