mirror of
https://github.com/trezor/trezor-suite.git
synced 2026-02-27 20:15:12 +01:00
feat(utils): add serializeError helper
This commit is contained in:
committed by
Jiri Zbytovsky
parent
4f51757421
commit
d391fde59d
@@ -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';
|
||||
|
||||
15
packages/utils/src/serializeError.ts
Normal file
15
packages/utils/src/serializeError.ts
Normal 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}`;
|
||||
};
|
||||
30
packages/utils/tests/serializeError.test.ts
Normal file
30
packages/utils/tests/serializeError.test.ts
Normal 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');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user