Effect CommunityEC
Effect Community3y ago
16 replies
Stephen Bluck

Handling Unauthorized Errors with Effect.orDie

Hey everyone. I have a little problem in which I hope you can help me solve. I use Effect.orDie in some places, for errors that I can't recover from which are mainly network errors, response errors and parsing errors. I have a situation where I need to check for an UnauthorizedError - this can happen if the token expires mid api call and in this case, I want to log the user out or refresh their token and retry. I don't want to pollute my domain with an UnauthorizedError in the E. Here is an example of my issue:
class UnauthorizedError {
  readonly _tag = 'UnauthorizedError';
}

const fetch = (n: number) =>
  Effect.gen(function* ($) {
    if (n === 0) {
      return yield $(Effect.fail(new UnauthorizedError()));
    }

    return { data: true };
  });

const getSomething = pipe(fetch(0), Effect.orDie);

const result = Effect.runPromise(getSomething).catch((e) => {
  /*
  I want to catch the UnauthorizedError and throw a redirect at the edge of my app
  I can't do this as an Error is thrown, not my UnauthorizedError
  */

  if (e instanceof UnauthorizedError) {
    throw redirect('/logout');
  }
});

I'm sure some of you must have encountered this problem before and am eager to find out how you solved it!
Was this page helpful?