UNPKG

2.21 kBJavaScriptView Raw
1/**
2 * Created by Andy Likuski on 2020.02.21
3 * Copyright (c) 2020 Andy Likuski
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6 *
7 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10 */
11import * as R from 'ramda';
12
13/**
14 * Stringify an error with a stack trace
15 * https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify
16 * @param {Object} err Error
17 * @return {string} The json stringified error
18 */
19export const stringifyError = err => {
20 // If the error isn't an Error object, wrap it
21 const wrappedError = wrapError(err);
22
23 const obj = R.fromPairs(R.map(
24 key => [key, wrappedError[key]],
25 Object.getOwnPropertyNames(wrappedError)
26 ));
27 // Use replace to convert escaped in stack \\n to \n
28 return R.replace(/\\n/g, '\n', JSON.stringify(
29 // Put message and stack first
30 R.merge(R.pick(['message', 'stack'], obj), R.omit(['message', 'stack'])),
31 null,
32 2
33 ));
34};
35
36/**
37 * Wraps an error in Error unless it already is an Error. Useful for Result.Error strings that need to be
38 * converted to errors
39 * @param {*} error The value to wrap if needed
40 * @return {Error} The wrapped error
41 */
42export const wrapError = error => {
43 return R.unless(
44 R.is(Error),
45 e => new Error(e)
46 )(error);
47};