errorUtils.js 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. // class that'll make all errors in the app categorisable into operational and non-operational errors
  2. /**
  3. * similar to Error class, but much cooler for this app
  4. */
  5. exports.AppError = class extends Error {
  6. /**
  7. *
  8. * @param {string} message message that'll show up on err.message
  9. * @param {number} statusCode err status code
  10. */
  11. constructor(message, statusCode) {
  12. super(message);
  13. this.statusCode = statusCode || 500;
  14. this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
  15. this.isOperational = true;
  16. // Error.captureStackTrace(this, this.constructor);
  17. }
  18. };
  19. // alternative for the ugly trycatch blocks
  20. /**
  21. * wrapper for async functions in the controller
  22. * @param {function} controller async function whose errors are to be caught
  23. * @returns a function similar to express's middleware which executes all the logic of the passed function
  24. */
  25. exports.catchErrors = function (controller) {
  26. return (req, res, next) => {
  27. controller(req, res, next).catch(err => next(err));
  28. };
  29. };