notFound.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * 404 (Not Found) Handler
  3. *
  4. * Usage:
  5. * return res.notFound();
  6. * return res.notFound(err);
  7. * return res.notFound(err, 'some/specific/notfound/view');
  8. *
  9. * e.g.:
  10. * ```
  11. * return res.notFound();
  12. * ```
  13. *
  14. * NOTE:
  15. * If a request doesn't match any explicit routes (i.e. `config/routes.js`)
  16. * or route blueprints (i.e. "shadow routes", Sails will call `res.notFound()`
  17. * automatically.
  18. */
  19. module.exports = function notFound (data, options) {
  20. // Get access to `req`, `res`, & `sails`
  21. var req = this.req;
  22. var res = this.res;
  23. var sails = req._sails;
  24. // Set status code
  25. res.status(404);
  26. // Log error to console
  27. if (data !== undefined) {
  28. sails.log.verbose('Sending 404 ("Not Found") response: \n',data);
  29. }
  30. else sails.log.verbose('Sending 404 ("Not Found") response');
  31. // Only include errors in response if application environment
  32. // is not set to 'production'. In production, we shouldn't
  33. // send back any identifying information about errors.
  34. if (sails.config.environment === 'production') {
  35. data = undefined;
  36. }
  37. // If the user-agent wants JSON, always respond with JSON
  38. if (req.wantsJSON) {
  39. return res.jsonx(data);
  40. }
  41. // If second argument is a string, we take that to mean it refers to a view.
  42. // If it was omitted, use an empty object (`{}`)
  43. options = (typeof options === 'string') ? { view: options } : options || {};
  44. // If a view was provided in options, serve it.
  45. // Otherwise try to guess an appropriate view, or if that doesn't
  46. // work, just send JSON.
  47. if (options.view) {
  48. return res.view(options.view, { data: data });
  49. }
  50. // If no second argument provided, try to serve the default view,
  51. // but fall back to sending JSON(P) if any errors occur.
  52. else return res.view('404', { data: data }, function (err, html) {
  53. // If a view error occured, fall back to JSON(P).
  54. if (err) {
  55. //
  56. // Additionally:
  57. // • If the view was missing, ignore the error but provide a verbose log.
  58. if (err.code === 'E_VIEW_FAILED') {
  59. sails.log.verbose('res.notFound() :: Could not locate view for error page (sending JSON instead). Details: ',err);
  60. }
  61. // Otherwise, if this was a more serious error, log to the console with the details.
  62. else {
  63. sails.log.warn('res.notFound() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err);
  64. }
  65. return res.jsonx(data);
  66. }
  67. return res.send(html);
  68. });
  69. };