issues/27: add formatApiError util and unit tests
This commit is contained in:
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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';
|
||||
}
|
||||
Reference in New Issue
Block a user