refactor: centralize API error notifications with a new useNotifyApiError hook
This commit is contained in:
@@ -16,9 +16,7 @@ interface UseApiErrorOptions {
|
||||
onReport?: (payload: ReportPayload) => void;
|
||||
}
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
const normalizeMessage = (error: unknown): string => {
|
||||
export const normalizeMessage = (error: unknown): string => {
|
||||
if (!error) return 'Something went wrong.';
|
||||
if (typeof (error as { trim?: () => string })?.trim === 'function') {
|
||||
return (error as { trim: () => string }).trim();
|
||||
@@ -31,7 +29,7 @@ const normalizeMessage = (error: unknown): string => {
|
||||
|
||||
const useApiError = ({
|
||||
logger = console,
|
||||
onReport = noop,
|
||||
onReport,
|
||||
}: UseApiErrorOptions = {}) => {
|
||||
return useCallback(
|
||||
(
|
||||
@@ -40,7 +38,9 @@ const useApiError = ({
|
||||
) => {
|
||||
const normalizedMessage = message || normalizeMessage(error);
|
||||
logger.error('[API]', normalizedMessage, error);
|
||||
onReport({ message: normalizedMessage, variant, retry, error });
|
||||
if (onReport) {
|
||||
onReport({ message: normalizedMessage, variant, retry, error });
|
||||
}
|
||||
return normalizedMessage;
|
||||
},
|
||||
[logger, onReport],
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useStatusToast, ToastVariant } from '../lib/context/StatusToastContext';
|
||||
import { normalizeMessage } from './useApiError';
|
||||
|
||||
const useNotifyApiError = () => {
|
||||
const { showToast } = useStatusToast();
|
||||
|
||||
return useCallback(
|
||||
(error: unknown, fallbackMessage?: string, variant: ToastVariant = 'error') => {
|
||||
const message = fallbackMessage || normalizeMessage(error);
|
||||
console.error('[API]', message, error);
|
||||
showToast(message, variant);
|
||||
},
|
||||
[showToast],
|
||||
);
|
||||
};
|
||||
|
||||
export default useNotifyApiError;
|
||||
Reference in New Issue
Block a user