Effect CommunityEC
Effect Communityβ€’2y agoβ€’
79 replies
sandromaglione

Handling Errors in TypeScript without Effect/Either/Option

Can someone explain to me how you are supposed to handle errors in typescript without Effect/Either/Option?

Is using multiple try/catch blocks the best (only?) solution? 🀨

export interface ApiResponse {
  id: number;
  name: string;
}

export class ResponseError extends Error {
  constructor() {
    super();
    this.name = "ResponseError";
  }
}

export class NoOkayError extends Error {
  constructor() {
    super();
    this.name = "NoOkayError";
  }
}

export class JsonError extends Error {
  constructor() {
    super();
    this.name = "JsonError";
  }
}

export class FormattingError extends Error {
  constructor() {
    super();
    this.name = "FormattingError";
  }
}

export const program = async () => {
  var response;
  try {
    response = await fetch(`${BASE_URL}/api`, { method: "GET" });
  } catch (_) {
    throw new ResponseError();
  }

  if (!response.ok) {
    throw new NoOkayError();
  }

  var json;
  try {
    json = await response.json();
  } catch (_) {
    throw new JsonError();
  }

  if (
    json["name"] === undefined ||
    json["id"] === undefined ||
    isNaN(Number(json["id"]))
  ) {
    throw new FormattingError();
  }

  return json as ApiResponse;
};
Was this page helpful?