Custom error class as Node module to send custom error response

Here I have created a custom error class in Node.js. I created this ErrorClass to send a custom api call error response.

I want to catch this class CustomError

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 want to convert this to node-module , but I don't understand how.

+3


source to share


2 answers


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

Quoting the bluebird documentation .

For a parameter to be considered the type of error you want to filter, the constructor must have a property .prototype

instanceof Error

.

Such a constructor can be minimally created as follows:

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

create your own error object like

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

      



I want to convert this to a node -module, but I don't understand how.

You just need to assign whatever you want to export as part of the module to module.exports

. In this case, most likely you can export the function CustomError

and you can do it like this:

module.exports = CustomError;

      

More on module.exports

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

+2


source


A node module is nothing more than an exported class. In your example, if you export the CustomError

ie class

module.exports = CustomError;

      



Then you will be able to import the module from another class

var CustomError = require("./CustomError");
...
throw new CustomError();

      

+1


source







All Articles