serverError.js 2.4 KB

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