Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does express's default error handler behaviour return stack traces to the client?

I'm trying to get the error handling in my http api server working correctly, and I don't understand node's error handling behaviour.

I've defined my own error object like so:

function ServerError(statusCode, err, message) {
    this.status = statusCode;

    if (err != undefined) {
        this.err = err;

        if (message != undefined) {
            this.message = message;
        }
        else {
            this.message = err.message || err;
        }
    }
}

ServerError.prototype = new Error();

I use this object like so, either in middleware or a handler:

function forceError() {
    return function(req, res, next) {
        next(new ServerError(500, "Internal error!"));
    }
}

Without any handler defined, this error gets printed to the console and is returned in the response body. This happens for things like TypeErrors as well as my own errors. This is bad, as it includes a stack trace and filenames/paths.

Why is express returning the stacktrace? I thought the default behaviour was just to crash, and so not leak any information on the server to clients.

like image 416
thecoop Avatar asked Jan 13 '23 02:01

thecoop


1 Answers

From your code and use of next, I assume you are using express, and so, this is rather an express question. Express will default to serving errors with stacktraces in development mode only, while logging, but not serving, them in production mode.

Try running your app in production mode:

$ NODE_ENV=production node app.js
like image 145
Linus Thiel Avatar answered Jan 16 '23 22:01

Linus Thiel