Handle errors by tag with catch
A tagged catch handles selected failures of an Effect by pattern: you write when arms in braces directly after catch. Each arm recovers from the failures its pattern matches, and every failure that no arm matches keeps failing with its own type. Use it when you recover from some error classes and let the rest reach the caller. VIP-75 defines the form.
error InvalidCode { input: string }
error ItemMissing { code: string }
error RateLimited { retryAfter: number }
effect function findItem(input: string): string!(InvalidCode | ItemMissing | RateLimited) {
if (input === "") throw new InvalidCode({ input })
if (input === "book") throw new ItemMissing({ code: "BOOK" })
if (input === "slow") throw new RateLimited({ retryAfter: 30 })
return "Fountain pen"
}
effect function label(input: string) {
return findItem(input) catch { when ItemMissing: "Out of catalog" }
}
// Inferred: string!(InvalidCode | RateLimited)
// Run in an effect function:
// try Console.log(try label("pen"))
// try Console.log(try label("book"))
// try Console.log((try flip(label("")))._tag)Fountain pen
Out of catalog
InvalidCodefindItem(input) catch { ... } runs findItem(input). On success, the expression yields the item. On an ItemMissing failure, it yields the arm's value. InvalidCode and RateLimited have no arm, so label still fails with them. As with every catch expression, you write no try before the operand.
Write the arms
effect function describe(input: string): string!! {
return findItem(input) catch {
when ItemMissing: "Out of catalog";
when InvalidCode(let error): `Bad code "${error.input}"`;
when { _tag: "RateLimited", let retryAfter }: `Retry in ${retryAfter} s`;
}
}
// Run in an effect function:
// try Console.log(try describe("book"))
// try Console.log(try describe(""))
// try Console.log(try describe("slow"))Out of catalog
Bad code ""
Retry in 30 sA tagged catch starts with { followed by when and a pattern, or by default:. Separate arms with ;. The ; after the last arm is optional, so a single arm fits on one line. The arms use the patterns of match. The following table lists the patterns that select and bind an error.
| Arm | Matches | Binds |
|---|---|---|
when ItemMissing: | An error of that class, by its _tag | Nothing |
when InvalidCode(let error): | An error of that class | The error as error |
when ItemMissing and let error: | An error of that class | The error as error |
when { _tag: "RateLimited", let retryAfter }: | An object with that _tag | The field retryAfter |
when RateLimited(let error) and if (error.retryAfter < 60): | An error of that class that passes the guard | The error as error |
default: | Every remaining failure | Nothing |
Use the object tag pattern for a tagged error that has no class in scope, such as an error object from an SDK.
Run Effects in an arm
error Unavailable { reason: string }
const waits: number[] = []
effect function recordWait(seconds: number) {
waits.push(seconds)
}
effect function withRetryNote(input: string) {
return findItem(input) catch {
when RateLimited(let error): try recordWait(error.retryAfter), "Try later";
when ItemMissing(let error): throw new Unavailable({ reason: error.code });
}
}
// Inferred: string!(InvalidCode | Unavailable)
// Run in an effect function:
// try Console.log(try withRetryNote("slow"))
// try Console.log(waits)
// try Console.log((try flip(withRetryNote("book")))._tag)Try later
[ 30 ]
UnavailableAn arm body is effect code. try runs an Effect inside the arm, and throw fails with a typed error, without an effect (error) => handler. An arm is one expression. The first arm uses a comma expression: it runs recordWait and then yields "Try later". The second arm replaces ItemMissing with Unavailable in the error type.
Unhandled tags stay in the error type
// expect-error: EK9201
effect function strict(input: string): string!! {
return findItem(input) catch { when ItemMissing: "Out of catalog" }
}Without a default: arm, the expression fails again with every error that no arm matches. The compiler removes the matched classes from the error type and keeps the rest. The sample declares string!!, a function that cannot fail, but InvalidCode and RateLimited remain, so the compiler reports EK9201.
To handle every remaining failure, add a default: arm as the last arm:
effect function labelOrFallback(input: string): string!! {
return findItem(input) catch {
when ItemMissing: "Out of catalog";
default: "Unavailable";
}
}
// Run in an effect function:
// try Console.log(try labelOrFallback("book"))
// try Console.log(try labelOrFallback("slow"))
// Output: Out of catalog
// Output: UnavailableWith default:, the error type is never, unless an arm throws or runs an Effect that can fail. A tagged catch handles expected failures only. Defects and interruption pass through it.
Comparison with the other catch forms
The following three functions have the same contract, string!(InvalidCode | RateLimited), and behave the same.
// expect-warning: EK4835
effect function tagged(input: string) {
return findItem(input) catch { when ItemMissing: "Out of catalog" }
}
effect function withMatch(input: string) {
return findItem(input) catch effect (error) => match (error) {
when ItemMissing: "Out of catalog";
default: throw error;
}
}
effect function withCatchTag(input: string) {
return try catchTag(findItem(input), "ItemMissing", () => succeed("Out of catalog"))
}
// Run in an effect function: try Console.log(try tagged("book"), try withMatch("book"), try withCatchTag("book"))
// Output: Out of catalog Out of catalog Out of catalogA tagged catch without default: means exactly the catch effect handler with a match and default: throw error;. The compiler flags try catchTag(...) with the lint warning EK4835, which asks for a catch form. The following table shows when to use each form.
| Form | Use it when |
|---|---|
e catch (error) => value | One handler maps every failure to a value. A throw in this handler is a compile error. |
e catch { when A: ...; } | You recover from selected error classes and the rest keep failing. |
e catch effect (error) => { ... } | The handler needs statements, or logic that is not a pattern match. |
Combine with other operators
effect function codeLength(input: string) {
return (findItem(input) catch { when ItemMissing(let error): error.code }).length
}
// Run in an effect function: try Console.log(try codeLength("book"))
// Output: 4A tagged catch binds like ??. To apply ??, ||, &&, a member access or a call to the result, parenthesize the whole catch expression. Without the parentheses, the compiler reports EK0512. A line break after the closing } ends the statement.
An object literal after catch is not a handler. e catch { fallback: 1 } and e catch {} report EK0509.
Rules and diagnostics
The following table lists the diagnostics for a tagged catch.
| Code | Condition |
|---|---|
EK0504 | A catch expression appears outside effect code. |
EK0505 | The operand starts with try, as in try e catch { ... }. Write e catch { ... }. |
EK0506 | The operand is not an Effect. |
EK0509 | The braces after catch hold no when or default: arm. |
EK0512 | The catch expression mixes with ??, || or &&, or a member access or call follows the closing }, without parentheses. |
EK0701 | Two arms have no ; between them. |
EK0707 | An arm follows default:. |
EK9201 | An unhandled error class escapes a written return type that excludes it. |
EK9204 | Warning: the operand cannot fail, so no arm ever runs. |