index.d.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import {Primitive, JsonObject} from 'type-fest';
  2. export type ErrorObject = {
  3. name?: string;
  4. stack?: string;
  5. message?: string;
  6. code?: string;
  7. } & JsonObject;
  8. /**
  9. Serialize an `Error` object into a plain object.
  10. Non-error values are passed through.
  11. Custom properties are preserved.
  12. Circular references are handled.
  13. @example
  14. ```
  15. import {serializeError} from 'serialize-error';
  16. const error = new Error('🦄');
  17. console.log(error);
  18. //=> [Error: 🦄]
  19. console.log(serializeError(error));
  20. //=> {name: 'Error', message: '🦄', stack: 'Error: 🦄\n at Object.<anonymous> …'}
  21. ```
  22. */
  23. export function serializeError<ErrorType>(error: ErrorType): ErrorType extends Primitive
  24. ? ErrorType
  25. : ErrorObject;
  26. /**
  27. Deserialize a plain object or any value into an `Error` object.
  28. `Error` objects are passed through.
  29. Non-error values are wrapped in a `NonError` error.
  30. Custom properties are preserved.
  31. Non-enumerable properties are kept non-enumerable (name, message, stack).
  32. Enumerable properties are kept enumerable (all properties besides the non-enumerable ones).
  33. Circular references are handled.
  34. @example
  35. ```
  36. import {deserializeError} from 'serialize-error';
  37. const error = deserializeError({
  38. message: 'aaa',
  39. stack: 'at <anonymous>:1:13'
  40. });
  41. console.log(error);
  42. // Error: aaa
  43. // at <anonymous>:1:13
  44. ```
  45. */
  46. export function deserializeError(errorObject: ErrorObject | unknown): Error;