error-utils.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. const constructors = new Map([
  2. [Error.name, Error],
  3. [EvalError.name, EvalError],
  4. [RangeError.name, RangeError],
  5. [ReferenceError.name, ReferenceError],
  6. [SyntaxError.name, SyntaxError],
  7. [TypeError.name, TypeError],
  8. [URIError.name, URIError]
  9. ]);
  10. export function deserialize (error: Electron.SerializedError): Electron.ErrorWithCause {
  11. if (error && error.__ELECTRON_SERIALIZED_ERROR__ && constructors.has(error.name)) {
  12. const constructor = constructors.get(error.name);
  13. const deserializedError = new constructor!(error.message) as Electron.ErrorWithCause;
  14. deserializedError.stack = error.stack;
  15. deserializedError.from = error.from;
  16. deserializedError.cause = exports.deserialize(error.cause);
  17. return deserializedError;
  18. }
  19. return error;
  20. }
  21. export function serialize (error: Electron.ErrorWithCause): Electron.SerializedError {
  22. if (error instanceof Error) {
  23. // Errors get lost, because: JSON.stringify(new Error('Message')) === {}
  24. // Take the serializable properties and construct a generic object
  25. return {
  26. message: error.message,
  27. stack: error.stack,
  28. name: error.name,
  29. from: process.type as Electron.ProcessType,
  30. cause: exports.serialize(error.cause),
  31. __ELECTRON_SERIALIZED_ERROR__: true
  32. };
  33. }
  34. return error;
  35. }