issues/27: add formatApiError util and unit tests

This commit is contained in:
Valery Petrov
2026-06-04 13:19:02 +03:00
parent cfd8a4d403
commit 052d843dbd
2 changed files with 46 additions and 0 deletions
+19
View File
@@ -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');
});
});
+27
View File
@@ -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';
}