UNPKG

769 BJavaScriptView Raw
1// @flow strict-local
2
3export type JSONError = {
4 message: string,
5 stack?: string,
6 name?: string
7};
8
9export function errorToJson(error: string | Error): JSONError {
10 if (typeof error === 'string') {
11 return {message: error};
12 }
13
14 let jsonError = {
15 message: error.message,
16 stack: error.stack,
17 name: error.name
18 };
19 // Add all custom codeFrame properties
20 Object.keys(error).forEach(key => {
21 // $FlowFixMe
22 jsonError[key] = error[key];
23 });
24 return jsonError;
25}
26
27export function jsonToError(
28 json: ?JSONError
29): void | (Error & {[string]: string}) {
30 if (json != null) {
31 let error = new Error(json.message);
32 Object.keys(json).forEach(key => {
33 // $FlowFixMe
34 error[key] = json[key];
35 });
36 return error;
37 }
38}