UNPKG

@toolpad/utils

Version:

Shared utilities used by Toolpad packages.

57 lines (55 loc) 1.39 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.errorFrom = errorFrom; exports.serializeError = serializeError; var _collections = require("./collections"); var _strings = require("./strings"); function serializeError(error) { const { message, name, stack, code } = error; return { message, name, stack, code }; } /** * Creates a javascript `Error` from an unknown value if it's not already an error. * Does a best effort at inferring a message. Intended to be used typically in `catch` * blocks, as there is no way to enforce only `Error` objects being thrown. * * ``` * try { * // ... * } catch (rawError) { * const error = errorFrom(rawError); * console.assert(error instanceof Error); * } * ``` */ function errorFrom(maybeError) { if (maybeError instanceof Error) { return maybeError; } if (typeof maybeError === 'object' && maybeError && (0, _collections.hasOwnProperty)(maybeError, 'message') && typeof maybeError.message === 'string') { return new Error(maybeError.message, { cause: maybeError }); } if (typeof maybeError === 'string') { return new Error(maybeError, { cause: maybeError }); } const message = (0, _strings.truncate)(String(JSON.stringify(maybeError)), 500); return new Error(message, { cause: maybeError }); }