Reputation: 3428
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
.
Upvotes: 2
Views: 140
Reputation: 3428
The problem was actually the fact that I was not returning an instance of Bluebird promise, but ES6 Promise(using fetch), I resolved it by wrapping fetch inside Bluebird Promise.resolve.
Upvotes: 0
Reputation: 707666
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;
}
Upvotes: 2