HttpErrorController.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const logger = require('logger-sharelatex')
  2. const OError = require('@overleaf/o-error')
  3. const HttpErrors = require('@overleaf/o-error/http')
  4. const AuthenticationController = require('../Authentication/AuthenticationController')
  5. function renderHTMLError(statusCode, publicInfo, res) {
  6. res.status(statusCode)
  7. if (statusCode === 404) {
  8. res.render('general/404', { title: 'page_not_found' })
  9. } else if (statusCode === 403) {
  10. res.render('user/restricted', { title: 'restricted' })
  11. } else if (statusCode >= 400 && statusCode < 500) {
  12. res.render('general/400', {
  13. title: 'Client Error',
  14. message: publicInfo.message
  15. })
  16. } else {
  17. res.render('general/500', { title: 'Server Error' })
  18. }
  19. }
  20. function renderJSONError(statusCode, publicInfo, res) {
  21. res.status(statusCode).json(publicInfo)
  22. }
  23. function renderError(error, req, res) {
  24. const publicInfo = OError.getFullInfo(error).public || {}
  25. switch (req.accepts(['html', 'json'])) {
  26. case 'html':
  27. renderHTMLError(error.statusCode, publicInfo, res)
  28. break
  29. case 'json':
  30. renderJSONError(error.statusCode, publicInfo, res)
  31. break
  32. default:
  33. res.sendStatus(error.statusCode)
  34. }
  35. }
  36. function logError(error, req) {
  37. const userId = AuthenticationController.getLoggedInUserId(req)
  38. let logLevel
  39. if (error.statusCode >= 400 && error.statusCode < 500) {
  40. logLevel = 'warn'
  41. } else {
  42. logLevel = 'error'
  43. }
  44. logger[logLevel]({ error, url: req.url, method: req.method, userId })
  45. }
  46. module.exports = {
  47. handleError(error, req, res, next) {
  48. // Only handles HttpErrors
  49. if (!(error instanceof HttpErrors.HttpError)) {
  50. return next(error)
  51. }
  52. logError(error, req)
  53. renderError(error, req, res)
  54. }
  55. }