Home > Mobile >  How to get error message after throw in ExpressJS/NodeJS?
How to get error message after throw in ExpressJS/NodeJS?

Time:12-23

I am trying to catch all error in middleware Expressjs but I am getting "[object Object]" returned in logging console. How I can get message (e.g: { statusCode: 404, message: 'Not Found' }) of this Error ?

app.use((req, res, next) => {
    throw new Error({ statusCode: 404, message: 'Not Found' });
});

app.use((err, req, res, next) => {
   console.log(err); // [object Object]
   console.log(JSON.stringify(err)) // "[object Object]"
});

CodePudding user response:

The Error constructor accepts a string, NOT an object. When you pass it an object, it then tries to use it as a string and you get [object Object] as the automatic string conversion associated with a plain object.

You can do this instead:

app.use((req, res, next) => {
    const e = new Error('Not Found');
    e.statusCode = 404;
    throw e;
});

Or, I find it easier to create my own little Error subclass that has the desired arguments for the constructor:

class MyError extends Error {
    constructor(msg, status) {
        super(msg);
        this.status = status;
    }
    toJSON() {
        // handle the fact that the message property is not
        // enumerable and won't be picked up by JSON.stringify()
        // on its own
        return JSON.stringify({message: this.message, status: this.status});
    }
}

app.use((req, res, next) => {
    throw new MyError('Not Found', 404);
});

Note: If you're trying to serialize an Error object to JSON, some of the properties of an Error object are non-enumerable which means they won't show up in a default JSON.stringify(). You can override/control that by providing a .toJSON() method on your custom Error class as shown here or only use enumerable properties on the object.

  • Related