1
0

errors.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // This is a subset of, and the counterpart to errors.go
  2. export const fetchOrThrow = async (url, options) => {
  3. const response = await fetch(url, options);
  4. if (response.status !== 200) {
  5. await throwAppError(response);
  6. }
  7. return response; // Promise!
  8. };
  9. export const throwAppError = async (response) => {
  10. if (response.status === 401 || response.status === 403) {
  11. console.log(`[Error] HTTP ${response.status}`, response);
  12. throw new UnauthorizedError();
  13. }
  14. const error = await maybeToJson(response);
  15. if (error?.code) {
  16. console.log(`[Error] HTTP ${response.status}, ntfy error ${error.code}: ${error.error || ""}`, response);
  17. if (error.code === UserExistsError.CODE) {
  18. throw new UserExistsError();
  19. } else if (error.code === TopicReservedError.CODE) {
  20. throw new TopicReservedError();
  21. } else if (error.code === AccountCreateLimitReachedError.CODE) {
  22. throw new AccountCreateLimitReachedError();
  23. } else if (error.code === IncorrectPasswordError.CODE) {
  24. throw new IncorrectPasswordError();
  25. } else if (error?.error) {
  26. throw new Error(`Error ${error.code}: ${error.error}`);
  27. }
  28. }
  29. console.log(`[Error] HTTP ${response.status}, not a ntfy error`, response);
  30. throw new Error(`Unexpected response ${response.status}`);
  31. };
  32. const maybeToJson = async (response) => {
  33. try {
  34. return await response.json();
  35. } catch (e) {
  36. return null;
  37. }
  38. };
  39. export class UnauthorizedError extends Error {
  40. constructor() {
  41. super("Unauthorized");
  42. }
  43. }
  44. export class UserExistsError extends Error {
  45. static CODE = 40901; // errHTTPConflictUserExists
  46. constructor() {
  47. super("Username already exists");
  48. }
  49. }
  50. export class TopicReservedError extends Error {
  51. static CODE = 40902; // errHTTPConflictTopicReserved
  52. constructor() {
  53. super("Topic already reserved");
  54. }
  55. }
  56. export class AccountCreateLimitReachedError extends Error {
  57. static CODE = 42906; // errHTTPTooManyRequestsLimitAccountCreation
  58. constructor() {
  59. super("Account creation limit reached");
  60. }
  61. }
  62. export class IncorrectPasswordError extends Error {
  63. static CODE = 40026; // errHTTPBadRequestIncorrectPasswordConfirmation
  64. constructor() {
  65. super("Password incorrect");
  66. }
  67. }