Expected Errors (effect)
Domain Errorを表す
回復可能
型レベルで追跡する
Effect.failで作る
https://effect.website/docs/error-management/expected-errors/
Effect<A, E, R>の第二型引数に現れるエラー
型レベルで追跡されるということ
回復可能
Errorの定義
code:ts
class HttpError {
readonly _tag = "HttpError"
}
classと_tagを使う
code:例.ts
import { Effect, Data } from "effect"
// Simulate fetching weather data
function fetchWeather(city: string): Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (city === "London") {
resolve("Sunny")
} else {
reject(new Error("Weather data not found for this location"))
}
}, 1_000)
})
}
// Custom error class to represent a network error,
// including the original error message.
class NetworkError extends Data.TaggedError("NetworkError")<{
message: string; // Original error message
}> {}
function getWeather(city: string) {
return Effect.tryPromise({
try: () => fetchWeather(city),
// 捕捉したエラーからメッセージを抽出し、NetworkErrorに含める
catch: (error) => {
console.log(error);
return new NetworkError({ message: String(error) })
}
})
}
// NetworkError型のカスタムエラーを生成するEffect
const weatherEffect = getWeather("Paris");
Effect.runPromise(weatherEffect)
.then((data) => console.log(The weather in London is: ${data}))
.catch((error) =>
console.error(Failed to fetch weather data: ${error.message})
);
/*
Output:
Failed to fetch weather data: Error: Weather data not found for this location
*/
Effect.failで自動的にError型はunionになる
https://effect.website/docs/error-management/expected-errors/#error-tracking
Short-Circuiting(短絡評価)
https://effect.website/docs/error-management/expected-errors/#short-circuiting
Effect.gen, Effect.flatMap, Effect.andThen などを使ってEffectを合成した場合
途中でエラーが発生すると、残りの処理はスキップされる
最初のエラーだけが返る(以降は実行されない)
code:ts
yield* task1
yield* task2 // ← ここで失敗すると task3 は実行されない
yield* task3
エラーの回復方法
https://effect.website/docs/error-management/expected-errors/#catching-all-errors
Effect.either, Effect.option
Error型を含むやつをEitherやOptionに変換する
Effect.catchAll
Effect.catchAllCause
特定のエラーだけ扱いたいとき
Effect.catchSome
Effect.catchIf
Effect.catchTag
Effect.catchTags
Effect.fn