tguard-js
    Preparing search index...

    Function normalizeError

    • Normalizes an unknown value into an Error instance.

      Parameters

      • x: unknown

        The value to normalize.

      Returns Error

      A normalized Error instance.

      This function converts any thrown value into a proper Error object. It preserves the original message when possible and attaches the original value for debugging purposes.

      Behavior:

      • If the value is already an Error, it is returned as-is
      • If the value is error-like ({ message: string }), it is converted
      • Otherwise, the value is stringified into an error message

      The original value is attached to the returned error as cause. If there is a stack trace in the provided value, it will be preserved.

      Input Output message
      new Error('msg') 'msg'
      { message: 'msg' } 'msg'
      'error' 'error'
      123 '123'
      null 'null'
      undefined 'undefined'
      try {
      throw { message: 'Something went wrong' };
      } catch (err) {
      const error = normalizeError(err);
      console.log(error.message); // 'Something went wrong'
      console.log(error.cause); // { message: 'Something went wrong' }
      }

      1.0