errorHandling.tsx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import React from 'react';
  2. import Alert from 'components/common/Alert/Alert';
  3. import toast, { ToastType } from 'react-hot-toast';
  4. import { ErrorResponse } from 'generated-sources';
  5. interface ServerResponse {
  6. status: number;
  7. statusText: string;
  8. url?: string;
  9. message?: ErrorResponse['message'];
  10. }
  11. export type ToastTypes = ToastType | 'warning';
  12. export const getResponse = async (
  13. response: Response
  14. ): Promise<ServerResponse> => {
  15. let body;
  16. try {
  17. body = await response.json();
  18. } catch (e) {
  19. // do nothing;
  20. }
  21. return {
  22. status: response.status,
  23. statusText: response.statusText,
  24. url: response.url,
  25. message: body?.message,
  26. };
  27. };
  28. interface AlertOptions {
  29. id?: string;
  30. title?: string;
  31. message: React.ReactNode;
  32. }
  33. export const showAlert = (
  34. type: ToastTypes,
  35. { title, message, id }: AlertOptions
  36. ) => {
  37. toast.custom(
  38. (t) => (
  39. <Alert
  40. title={title || ''}
  41. type={type}
  42. message={message}
  43. onDissmiss={() => toast.remove(t.id)}
  44. />
  45. ),
  46. { id }
  47. );
  48. };
  49. export const showSuccessAlert = (options: AlertOptions) => {
  50. showAlert('success', {
  51. ...options,
  52. title: options.title || 'Success',
  53. });
  54. };
  55. export const showServerError = async (
  56. response: Response,
  57. options?: AlertOptions
  58. ) => {
  59. let body: Record<string, string> = {};
  60. try {
  61. body = await response.json();
  62. } catch (e) {
  63. // do nothing;
  64. }
  65. if (response.status) {
  66. showAlert('error', {
  67. id: response.url,
  68. title: `${response.status} ${response.statusText}`,
  69. message: body?.message || 'An error occurred',
  70. ...options,
  71. });
  72. } else {
  73. showAlert('error', {
  74. id: 'server-error',
  75. title: `Something went wrong`,
  76. message: 'An error occurred',
  77. ...options,
  78. });
  79. }
  80. };