mansona / express-autoroute

Helper module to automatically load Express routes from a structured routes/ folder
MIT License
35 stars 10 forks source link

Error handler functions set before routes #10

Closed ghost closed 10 years ago

ghost commented 10 years ago

Hi,

I have an issue with one of my error handler functions which is set before autoroute do his job. When I try to request an endpoint, I always get stuck in the error handler function. Here is my function to create a server :

function Server(options) {
    this.httpServer = null;
    this.server = express();

    this.server.set("port", options.port);
    this.server.set("name", options.name);

    this.server.use(express.bodyParser());
    this.server.use(express.methodOverride());

    autoroute(this.server, {
        throwErrors: true,
        logger: Logger,
        routesDir: path.join(__dirname, "routes")
    });

    this.server.use(resourceNotFoundHandler);
    this.server.use(errorHandler);

    this.httpServer = http.createServer(this.server);
}

The code of resourceNotFoundHandler and errorHandler functions :

function resourceNotFoundHandler(req, res, next) {
    var message = "Resource " + req.path + " not found";
    Logger.info(message);
    res.json(404, { error: message });
}

function errorHandler(err, req, res, next) {
}

I got this message for all requests :

{
    "error": "Resource /1/something/here not found"
}

Any idea ?

mansona commented 10 years ago

Ok i see the problem here. You are missing the use(server.router) call before your error handlers.

this.server.use(this.server.router);
this.server.use(resourceNotFoundHandler);
this.server.use(errorHandler);

If you look here you will see that this is necessary to tell express that the router is first in the order of middlewares.

Let me know that this works for you and I will close the issue. Cheers.

ghost commented 10 years ago

Work great now, thank you for this information.