From 052d843dbd354338275d96b1e00164661aa04eaa Mon Sep 17 00:00:00 2001 From: Valery Petrov Date: Thu, 4 Jun 2026 13:19:02 +0300 Subject: [PATCH] issues/27: add formatApiError util and unit tests --- src/utils/__test__/formatApiError.test.js | 19 ++++++++++++++++ src/utils/formatApiError.js | 27 +++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 src/utils/__test__/formatApiError.test.js create mode 100644 src/utils/formatApiError.js diff --git a/src/utils/__test__/formatApiError.test.js b/src/utils/__test__/formatApiError.test.js new file mode 100644 index 0000000..8e740a8 --- /dev/null +++ b/src/utils/__test__/formatApiError.test.js @@ -0,0 +1,19 @@ +import { formatApiError } from '../formatApiError'; + +describe('formatApiError', () => { + it('returns string errors as-is', () => { + expect(formatApiError('bad')).toBe('bad'); + }); + + it('reads RTK-style data.message', () => { + expect(formatApiError({ data: { message: 'Validation failed' } })).toBe('Validation failed'); + }); + + it('reads axios-style response.data.error', () => { + expect(formatApiError({ response: { data: { error: 'Unauthorized' } } })).toBe('Unauthorized'); + }); + + it('falls back to error.message', () => { + expect(formatApiError({ message: 'Network' })).toBe('Network'); + }); +}); diff --git a/src/utils/formatApiError.js b/src/utils/formatApiError.js new file mode 100644 index 0000000..97f3c27 --- /dev/null +++ b/src/utils/formatApiError.js @@ -0,0 +1,27 @@ +/** + * Normalize API error payload for UI (RTK Query / axios). + * @param {unknown} error + * @returns {string} + */ +export function formatApiError(error) { + if (!error) { + return 'Unknown error'; + } + if (typeof error === 'string') { + return error; + } + const data = error?.data ?? error?.response?.data; + if (typeof data === 'string') { + return data; + } + if (data?.message) { + return String(data.message); + } + if (data?.error) { + return String(data.error); + } + if (error?.message) { + return String(error.message); + } + return 'Request failed'; +}