Search code examples
javascriptnode.jsbluebirdnode-modulescustom-error-handling

Custom Error Class as a Node module to send custom error response


Here I created Custom Error class in Node.js. I created this ErrorClass to send Custom error response of api call.

I want to catch this CustomError class in Bluebird Catch promises.

Object.defineProperty(Error.prototype, 'message', {
    configurable: true,
    enumerable: true
});

Object.defineProperty(Error.prototype, 'stack', {
    configurable: true,
    enumerable: true
});

Object.defineProperty(Error.prototype, 'toJSON', {
    value: function () {
        var alt = {};
        Object.getOwnPropertyNames(this).forEach(function (key) {
            alt[key] = this[key];
        }, this);

        return alt;
    },
    configurable: true
});

Object.defineProperty(Error.prototype, 'errCode', {
    configurable: true,
    enumerable: true
});

function CustomError(errcode, err, message) {
    Error.captureStackTrace(this, this.constructor);
    this.name = 'CustomError';
    this.message = message;
    this.errcode = errcode;
    this.err = err;
}

CustomError.prototype = Object.create(Error.prototype);

I wanna convert this into node-module but I am not getting how to do that.


Solution

  • I want to catch this CustomError class in Bluebird Catch promises.

    Quoting bluebird's documentation,

    For a parameter to be considered a type of error that you want to filter, you need the constructor to have its .prototype property be instanceof Error.

    Such a constructor can be minimally created like so:

    function MyCustomError() {}
    MyCustomError.prototype = Object.create(Error.prototype);
    

    Using it:

    Promise.resolve().then(function() {
        throw new MyCustomError();
    }).catch(MyCustomError, function(e) {
        //will end up here now
    });
    

    So, you can catch the custom error object, like this

    Promise.resolve().then(function() {
        throw new CustomError();
    }).catch(CustomError, function(e) {
        //will end up here now
    });
    

    I wanna convert this into node-module but I am not getting how to do that.

    You just have to assign whatever you want to export as part of the module, to module.exports. In this case, most likely, you might want to export the CustomError function and it can be done like this

    module.exports = CustomError;
    

    Read more about module.exports in this question, What is the purpose of Node.js module.exports and how do you use it?