简体   繁体   中英

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;

I have this custom exception and I throw it at some point, but when I try to catch it in promise like

import ApiError from './ApiError';
...
.catch(ApiError, (e) => {
    console.log('api error');
})
.catch((e) => {
    console.log(e); <= this is undefined(in ApiError)
});

the error is delegated to generic catch with error saying that message cannot be assigned to undefined( this=undefined in ApiError), what am I doing wrong here ?

EDIT: The problem was actually the fact that I was not returning an instance of Bluebird promise, but Node Promise (using fetch ), I resolved it by wrapping fetch inside Bluebird Promise.resolve .

That error sounds like you aren't creating the instance of your ApiError object properly.

When you throw one of your errors, it should be:

throw new ApiError(xxx);

Note, the new that must be used. The specifics of your error make it appear like you aren't using the new .


Alternatively, you could change the implementation of your ApiError constructor so that you could do;

throw ApiError(xxx);

But, you'd have to change ApiError to detect whether it was called with new or not and if not, then call new itself.

function ApiError(response) {
  if (!(this instanceof ApiError)) {
      return new ApiError(response);
  }
  this.message = 'API error';
  this.response = response;
}

Or, in ES6, you can use the new.target option:

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 中解决了这个问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM