Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sails.js: call 404 manually

I'm looking for a way to use the default 404 error provided by sails.js framework.

The doc is here http://sailsjs.org/#!documentation/config.404 but I'm wondering how I can call the 404 method from another controller.

Of course I could use the code in the doc, but I would have prefered to use the dedicated framework method.

like image 312
Vadorequest Avatar asked May 23 '26 13:05

Vadorequest


2 Answers

res.notFound() should do the trick for version 0.10.

Have a look at your api/responses/ folder, it contains the default error response helpers for sails and allows you to come up with your own response types by saving files there.

Included by default:

/api/responses
    badRequest.js  - 400 - res.badRequest()
    notFound.js    - 404 - res.notFound()
    forbidden.js   - 403 - res.forbidden()
    serverError.js - 500 - res.serverError()

Roll your own:

/api/responses
   notAcceptable.js - res.notAcceptable();

Example (modified api/responses/notFound.js):

module.exports = function notAcceptable() {
    var req = this.req;
    var res = this.res;

    var viewFilePath = 405;
    var statusCode = 405;

    var result = {
      status: statusCode
    };

    if (req.wantsJSON) {
        return res.json(result, result.status);
    }
    res.status(result.status);
    res.render(viewFilePath, function(err) {
        if (err) {
            return res.json(result, result.status);
        }

        res.render(viewFilePath);
    });
};
like image 71
marionebl Avatar answered May 26 '26 04:05

marionebl


The pageNotFound method, described in documentation is just default implementation of 404 responding behavior and is part of sails config. You can see it in config/404.js file. If you want to call it from your controller, you can refer to it the same way as you refer any other sails config variables:

yourControllerAction: function(req, res) {
  ......
  // if  content not found, calling 404 method
  sails.config[404](req, res);
  // else
  res.send('Some content');
},
like image 34
ataman Avatar answered May 26 '26 03:05

ataman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!