errors.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // @ts-check
  2. /**
  3. * Typed as a string because otherwise it's a const string, which means we can't
  4. * override it in let statements.
  5. * @type {string}
  6. */
  7. export const UNEXPECTED_ERROR_MESSAGE = 'An unexpected error occurred';
  8. /**
  9. * Extracts the status and message properties from the error object, if
  10. * available for public use. The `unknown` is for catch statements
  11. * @param {Error | AuthenticationError | RequestError | unknown} err
  12. */
  13. export function extractStatusAndMessage(err) {
  14. let statusCode = 500;
  15. let errorMessage = UNEXPECTED_ERROR_MESSAGE;
  16. if (err instanceof AuthenticationError || err instanceof RequestError) {
  17. statusCode = err.status;
  18. errorMessage = err.message;
  19. }
  20. return { statusCode, errorMessage };
  21. }
  22. export class RequestError extends Error {
  23. /**
  24. * @param {string} message
  25. */
  26. constructor(message) {
  27. super(message);
  28. this.name = "RequestError";
  29. this.status = 400;
  30. }
  31. }
  32. export class AuthenticationError extends Error {
  33. /**
  34. * @param {string} message
  35. */
  36. constructor(message) {
  37. super(message);
  38. this.name = "AuthenticationError";
  39. this.status = 401;
  40. }
  41. }