typescript / intermediate
Snippet
Handling Async Operations with Type-Safe Result Objects
Instead of relying on unhandled promise rejections, this pattern wraps asynchronous operation outcomes into typed success or failure result objects. It provides structured error handling using custom Error classes.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class NetworkError extends Error {constructor(message: string, public readonly statusCode: number) {super(message);this.name = "NetworkError";}}type AsyncResult<T> =| { success: true; data: T }| { success: false; error: NetworkError };async function fetchUserData(id: number): Promise<AsyncResult<{ name: string }>> {try {if (id <= 0) {throw new NetworkError("Invalid user ID provided", 400);}return { success: true, data: { name: "Alice" } };} catch (err) {const error = err instanceof NetworkError ? err : new NetworkError("Unknown error", 500);return { success: false, error };}}
Breakdown
1
class NetworkError extends Error {
Defines a custom error class extending the built-in Error class.
2
type AsyncResult<T> =
Creates a container type representing either a successful output or a NetworkError object.
3
async function fetchUserData(id: number): Promise<AsyncResult<{ name: string }>> {
Declares an async function returning a promise resolved to the typed result object.
4
const error = err instanceof NetworkError ? err : new NetworkError("Unknown error", 500);
Ensures caught exceptions strictly conform to the expected NetworkError type.