feat(utils): add serializeError helper

This commit is contained in:
Jiri Zbytovsky
2025-01-28 08:53:02 +01:00
committed by Jiri Zbytovsky
parent 4f51757421
commit d391fde59d
3 changed files with 46 additions and 0 deletions

View File

@@ -46,6 +46,7 @@ export * from './promiseAllSequence';
export * from './redactUserPath';
export * from './resolveAfter';
export * from './scheduleAction';
export * from './serializeError';
export * from './splitStringEveryNCharacters';
export * from './throttler';
export * from './throwError';

View File

@@ -0,0 +1,15 @@
/**
* Serialize an error of unknown type to a string.
*/
export const serializeError = (error: unknown): string => {
// Error instances are objects, but have no JSON printable properties
if (error instanceof Error) {
return error.toString();
}
if (typeof error === 'object') {
return JSON.stringify(error);
}
// assumed to be a primitive type; exotic types such as function will also be simply stringified
return `${error}`;
};

View File

@@ -0,0 +1,30 @@
import { serializeError } from '../src/serializeError';
class CustomError extends Error {
somethingExtra = 'extra stuff';
toString() {
return `${super.toString()} + ${this.somethingExtra} `;
}
}
describe(serializeError.name, () => {
it('serializes an Error instance', () => {
const error = new Error('example message');
expect(serializeError(error)).toBe('Error: example message');
const customError = new CustomError('example message');
expect(serializeError(customError)).toBe('Error: example message + extra stuff ');
});
it('serializes a plain object', () => {
const error = { message: 'test' };
expect(serializeError(error)).toBe(JSON.stringify(error));
});
it('serializes a primitive', () => {
expect(serializeError('test')).toBe('test');
expect(serializeError(123)).toBe('123');
expect(serializeError(false)).toBe('false');
});
});