yorkie-js-sdk icon indicating copy to clipboard operation
yorkie-js-sdk copied to clipboard

Unify Error Throwing Methods

Open chacha912 opened this issue 2 years ago • 0 comments

Description:

yorkie-js-sdk uses three different methods for throwing errors. Let's pick one way to throw errors and apply it consistently across yorkie-js-sdk. If there's a better approach, let's talk about it and see if we should switch.

  1. throw new Error:

Generates a general error using the throw statement. This is a straightforward and common method.

throw new Error('This is a general error.');
  1. throw new YorkieError:

Creates and throws a custom error, allowing additional information to be added to the error. This approach helps identify errors originating from Yorkie, provides a way to categorize errors, but requires handling of error codes for each case.

// src/util/error.ts
export class YorkieError extends Error {
  name = 'YorkieError';
  stack?: string;

  constructor(readonly code: Code, readonly message: string) {
    super(message);
    this.toString = (): string =>
      `${this.name}: [code=${this.code}]: ${this.message}`;
  }
}

throw new YorkieError(Code.Unsupported, `unsupported type: ${valueType}`);
  1. logger.fatal():

Records errors using the logger with the fatal level. Different processing can be applied based on log levels.

// src/util/logger.ts
export const logger = {
  fatal: (message: string, ...messages: Array<unknown>): void => {
    if (typeof console !== 'undefined') {
      if (typeof console.error !== 'undefined') {
        console.error('YORKIE F:', ...messages);
      } else {
        console.log('YORKIE F:', ...messages);
      }
    }

    throw new Error(`YORKIE F: ${message}`);
  },
  // Other log levels like debug, info, warn, error, etc.
};

logger.fatal('This is a fatal error.');

However, note that an error is being thrown within logger.fatal. This can lead to TypeScript errors when using the method, as showed in the example below:

// operation.ts
public getExecutedAt(): TimeTicket {
  if (!this.executedAt) {
    logger.fatal(`executedAt has not been set yet`);
  }
  return this.executedAt; 
// ^^^^^^  Type 'TimeTicket | undefined' is not assignable to type 'TimeTicket'.
}

Why:

Standardize the error-throwing approach for consistency and clarity throughout the yorkie-js-sdk codebase.

chacha912 avatar Nov 27 '23 10:11 chacha912