badRequest.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * 400 (Bad Request) Handler
  3. *
  4. * Usage:
  5. * return res.badRequest();
  6. * return res.badRequest(data);
  7. * return res.badRequest(data, 'some/specific/badRequest/view');
  8. *
  9. * e.g.:
  10. * ```
  11. * return res.badRequest(
  12. * 'Please choose a valid `password` (6-12 characters)',
  13. * 'trial/signup'
  14. * );
  15. * ```
  16. */
  17. module.exports = function badRequest(data, options) {
  18. // Get access to `req`, `res`, & `sails`
  19. var req = this.req;
  20. var res = this.res;
  21. var sails = req._sails;
  22. // Set status code
  23. res.status(400);
  24. // Log error to console
  25. if (data !== undefined) {
  26. sails.log.verbose('Sending 400 ("Bad Request") response: \n',data);
  27. }
  28. else sails.log.verbose('Sending 400 ("Bad Request") response');
  29. // Only include errors in response if application environment
  30. // is not set to 'production'. In production, we shouldn't
  31. // send back any identifying information about errors.
  32. if (sails.config.environment === 'production') {
  33. data = undefined;
  34. }
  35. // If the user-agent wants JSON, always respond with JSON
  36. if (req.wantsJSON) {
  37. return res.jsonx(data);
  38. }
  39. // If second argument is a string, we take that to mean it refers to a view.
  40. // If it was omitted, use an empty object (`{}`)
  41. options = (typeof options === 'string') ? { view: options } : options || {};
  42. // If a view was provided in options, serve it.
  43. // Otherwise try to guess an appropriate view, or if that doesn't
  44. // work, just send JSON.
  45. if (options.view) {
  46. return res.view(options.view, { data: data });
  47. }
  48. // If no second argument provided, try to serve the implied view,
  49. // but fall back to sending JSON(P) if no view can be inferred.
  50. else return res.guessView({ data: data }, function couldNotGuessView () {
  51. return res.jsonx(data);
  52. });
  53. };