2
0

http-error-handler.js 882 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { HttpError } from 'http-errors';
  2. import loggerFactory from '~/utils/logger';
  3. const logger = loggerFactory('growi:middleware:htto-error-handler');
  4. const isHttpError = (val) => {
  5. if (!val || typeof val !== 'object') {
  6. return false;
  7. }
  8. if (val instanceof HttpError) {
  9. return true;
  10. }
  11. return val instanceof Error
  12. && typeof val.expose === 'boolean'
  13. && typeof val.statusCode === 'number'
  14. && val.status === val.statusCode;
  15. };
  16. module.exports = async(err, req, res, next) => {
  17. // handle if the err is a HttpError instance
  18. if (isHttpError(err)) {
  19. const httpError = err;
  20. try {
  21. return res
  22. .status(httpError.status)
  23. .send({
  24. status: httpError.status,
  25. message: httpError.message,
  26. });
  27. }
  28. catch (err) {
  29. logger.error('Cannot call res.send() twice:', err);
  30. }
  31. }
  32. next(err);
  33. };