ChemPal Documentation - v1.17.0
    Preparing search index...

    Function getErrorMessage

    • Reads a human-readable message from anything that can be thrown. A catch variable is typed unknown, so error.message doesn't type-check; this narrows it safely. Used to put the cause in a logger call's message (see the last example).

      Parameters

      • error: unknown

        Whatever was thrown or rejected with

      Returns string

      An Error's message (its name when the message is empty), a string as-is, or the string form of anything else; "Unknown error" if even that fails

      getErrorMessage(new TypeError('bad input')); // 'bad input'
      getErrorMessage(new Error('')); // 'Error'
      getErrorMessage('user_aborted'); // 'user_aborted'
      getErrorMessage({ code: 1 }); // '[object Object]'
      getErrorMessage(undefined); // 'undefined'

      // In a logger call, message first and the error itself in the object:
      logger.warn(`Failed to load: ${getErrorMessage(error)}`, { error });
      export function getErrorMessage(error: unknown): string {
      if (error instanceof Error) {
      return error.message || error.name;
      }
      if (typeof error === 'string') {
      return error;
      }
      try {
      return String(error);
      } catch {
      // e.g. an object with a null prototype has no toString.
      return 'Unknown error';
      }
      }