refactor: centralize API error notifications with a new useNotifyApiError hook

This commit is contained in:
2025-12-07 23:55:47 +01:00
parent 595c170c00
commit d46db2c701
14 changed files with 59 additions and 55 deletions
+5 -5
View File
@@ -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],
+18
View File
@@ -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;