HttpErrorController.js 1.6 KB

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