HttpErrorHandler.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. const logger = require('logger-sharelatex')
  2. function renderJSONError(res, message, info) {
  3. const fullInfo = { ...info, message }
  4. if (info.message) {
  5. logger.warn(
  6. info,
  7. `http error info shouldn't contain a 'message' field, will be overridden`
  8. )
  9. }
  10. res.json(fullInfo)
  11. }
  12. module.exports = {
  13. badRequest(req, res, message, info) {
  14. res.status(400)
  15. switch (req.accepts(['html', 'json'])) {
  16. case 'html':
  17. return res.render('general/400', {
  18. title: 'Client Error',
  19. message: message
  20. })
  21. case 'json':
  22. return renderJSONError(res, message, info || {})
  23. default:
  24. return res.send('client error')
  25. }
  26. },
  27. conflict(req, res, message, info) {
  28. res.status(409)
  29. switch (req.accepts(['html', 'json'])) {
  30. case 'html':
  31. return res.render('general/400', {
  32. title: 'Client Error',
  33. message: message
  34. })
  35. case 'json':
  36. return renderJSONError(res, message, info || {})
  37. default:
  38. return res.send('conflict')
  39. }
  40. },
  41. forbidden(req, res, message = 'restricted', info = {}) {
  42. res.status(403)
  43. switch (req.accepts(['html', 'json'])) {
  44. case 'html':
  45. return res.render('user/restricted', { title: 'restricted' })
  46. case 'json':
  47. return renderJSONError(res, message, info)
  48. default:
  49. return res.send('restricted')
  50. }
  51. },
  52. notFound(req, res, message = 'not found', info = {}) {
  53. res.status(404)
  54. switch (req.accepts(['html', 'json'])) {
  55. case 'html':
  56. return res.render('general/404', { title: 'page_not_found' })
  57. case 'json':
  58. return renderJSONError(res, message, info)
  59. default:
  60. return res.send('not found')
  61. }
  62. },
  63. unprocessableEntity(req, res, message = 'unprocessable entity', info = {}) {
  64. res.status(422)
  65. switch (req.accepts(['html', 'json'])) {
  66. case 'html':
  67. return res.render('general/400', {
  68. title: 'Client Error',
  69. message: message
  70. })
  71. case 'json':
  72. return renderJSONError(res, message, info)
  73. default:
  74. return res.send('unprocessable entity')
  75. }
  76. },
  77. legacyInternal(req, res, message, error) {
  78. logger.error(error)
  79. res.status(500)
  80. switch (req.accepts(['html', 'json'])) {
  81. case 'html':
  82. return res.render('general/500', { title: 'Server Error' })
  83. case 'json':
  84. return renderJSONError(res, message, {})
  85. default:
  86. return res.send('internal server error')
  87. }
  88. }
  89. }