Result Type Async Error Handling
Replace thrown exceptions with a Result union for expected failures, chaining async operations without try-catch pyramids or lost errors.
Code
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
const ok = <T>(value: T): Result<T, never> => ({ ok: true, value });
const err = <E>(error: E): Result<never, E> => ({ ok: false, error });
class ValidationError {
constructor(readonly field: string, readonly reason: string) {}
}
async function fetchUser(id: string): Promise<Result<{ id: string; email: string }, Error>> {
if (!/^[a-z0-9-]+$/.test(id)) {
return err(new ValidationError('id', 'invalid characters'));
}
const res = await fetch('https://api.example.com/users/' + id);
if (!res.ok) {
return err(new Error('upstream status ' + res.status));
}
return ok(await res.json());
}
async function mapResult<T, U, E>(
result: Result<T, E>, fn: (value: T) => Promise<U>,
): Promise<Result<U, E>> {
if (!result.ok) return result;
return ok(await fn(result.value));
}
const user = await fetchUser('u-123');
const decorated = await mapResult(user, async (u) => ({ ...u, email: u.email.toUpperCase() }));
if (decorated.ok) {
console.log('email:', decorated.value.email);
} else if (decorated.error instanceof ValidationError) {
console.log('field problem:', decorated.error.field);
} else {
console.log('failure:', decorated.error.message);
}How it works
Structurally, expect the class ValidationError and the functions fetchUser and mapResult and nothing else.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Points of care
fetchexist only in browsers — a Node runtime has no shims for them out of the box.- The guard
!res.okshort-circuits the flow with an earlyreturnwhen its condition holds.
Putting it to use
The primary signature is async function fetchUser(id: string)
The demo output is labeled (email:, field problem:, failure:), so each printed line points back to the operation it originated from.
Core lines
const decorated = await mapResult(user, async (u) => ({ ...u, email: u.email.toUpperCase() }));
return ok(await fn(result.value));
return ok(await res.json());
Interactive Tools for This Topic
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `fetchUser`, `mapResult` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.