Now we are ready to introduce catchTag.
Effect.catchTag allows to handle a single error:
- The first parameter is the "tag" of the error that we want to handle
- The second parameter is a function that gives us the error and returns an
Effectto handle it
const main = fetchRequest.pipe(
Effect.flatMap(jsonResponse),
Effect.catchTag(
"UnknownException", // 👈 Error to catch
(unknownException) => /** Handle error */
)
);In this example we catch the
"UnknownException"error.
unknownExceptionmay come from eitherfetchRequestorjsonResponse, since they both can fail withUnknownException.
Inside catchTag we need to return another Effect that "recovers" from the error.
Recovering from an error simply means executing another effect if that specific error happens, for example:
- Make an alternative request to fetch the same resource
- Provide a default value
- Ignore the error and continue the execution
In this example we can handle the error by using Effect.succeed:
const main = fetchRequest.pipe(
Effect.flatMap(jsonResponse),
Effect.catchTag("UnknownException", () =>
Effect.succeed("There was an error")
)
);
Effect.runPromise(main).then(console.log);Now when we run the program instead of an exception we will see our error message:
> effect-getting-started-course@1.0.0 dev
> tsx src/index.ts
There was an errorWhy Effect.succeed in an error?
Before running an Effect we can decide to handle some or all the errors in the error parameter (Effect<Success, ErrorParameter>).
Handling an error means "removing" it from ErrorParameter and moving it to Success. In practice this means returning another Effect that succeeds and adding its result to the success parameter:
/// Effect<Response, UnknownException>
const main = fetchRequest;
// 👆 From `Response` to `Response | string` 👇
/// Effect<Response | string, never>
const main = fetchRequest.pipe(
Effect.catchTag("UnknownException", () =>
Effect.succeed<string>("There was an error")
)
);
catchTagaccepts any effect. It's perfectly valid for the given effect to also fail. In that case its error is added insideErrorParameter.
