All files / src/errors toError.ts

87.5% Statements 7/8
88.88% Branches 8/9
100% Functions 1/1
87.5% Lines 7/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23  13x 11x           2x 1x     1x       1x 1x          
export function toError(error: unknown): Error {
  if (error instanceof Error) {
    return error
  }
 
  // Some runtimes (and cross-realm values, e.g. errors surfaced from native
  // bindings) are error-like without being `Error` instances. Normalize them
  // into a real `Error` while preserving the original message.
  if (typeof error === 'object' && error !== null && 'message' in error) {
    return new Error(String(error.message))
  }
 
  const message = String(error)
 
  // Objects without `message` or `toString()` will return '[object Object]',
  // JSON-stringify them explicitly to preserve the original content.
  Eif (message === '[object Object]') {
    return new Error(JSON.stringify(error))
  }
 
  return new Error(message)
}