Question

I'm new to Node and Sails and have been struggling with this problem for a couple of weeks now. I need to log (eventually to a file or database) all errors that occur in our Sails app. I have found a couple of answers that come close to solving this, but none seem to work 100%. I have setup things based off of the answer from this question

When using Sails v0.9.16 I setup my logging in the config/500.js file, but when using test code...

t.t;

... in my controller, Sails just prints out "ReferenceError: t is not defined". It never goes to 500.js. In Sails v0.10.0-rc5 the same test code will get to my custom 500 middleware (shown below).

Problem is in Sails v0.10.0-rc5 it appears that the middleware Router handles 400 error message before getting to my custom 400 middleware.

We have not committed to which version we are going to use, but getting this to work in one or the other would probably make up our minds.

So how do I get all errors that happen? If I am on the right track, what am I missing to get this to work?

Thanks in advance!

Not much code to show for v0.9.16...I don't think I changed anything other than adding a sails.log in the 500.js file...

Below is the custom middleware setup for v0.10.0-rc5 ...

    loadMiddleware: function(app, defaultMiddleware, sails) {

    // Use the middleware in the correct order
        app.use(defaultMiddleware.startRequestTimer);
        app.use(defaultMiddleware.cookieParser);
        app.use(defaultMiddleware.session);
        app.use(defaultMiddleware.bodyParser);
        app.use(defaultMiddleware.handleBodyParserError);
        app.use(defaultMiddleware.methodOverride);
        app.use(defaultMiddleware.poweredBy);

        app.use(defaultMiddleware.router); //400s do not make it past this...
        app.use(defaultMiddleware.www);
        app.use(defaultMiddleware.favicon);

        app.use(function(req, res, next ) {
            sails.log("400 error caught in middleware - " + err.stack);         
            next();
        });

        app.use(function(err, req, res, next){
            sails.log("500 error caught in middleware - " + err.stack);
            next(err);
        });
}
Was it helpful?

Solution

In Sails v0.10, you have custom responses to handle errors, so you don't need to provide custom middleware as in your example. By default, most errors (i.e. those not specifically triggered by res.forbidden(), res.notFound() or another handler) will be served by the serverError response that lives in api/responses/serverError.js. You can customize this to do whatever you like.

If you've upgraded a v0.9 app to v0.10, you might not have the api/responses folder. No problem; just use sails new whatever in an empty directory to generate a new v0.10 project and copy the api/responses folder from the new project to your old one!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top