Skip to content

Instantly share code, notes, and snippets.

@maddsua
Created February 26, 2025 16:28
Show Gist options
  • Select an option

  • Save maddsua/04e1e41a1114e9d5a58baa104fbe290c to your computer and use it in GitHub Desktop.

Select an option

Save maddsua/04e1e41a1114e9d5a58baa104fbe290c to your computer and use it in GitHub Desktop.
type Expect<T> = {
result: T;
error: null;
} | {
result: null;
error: Error;
};
type Result<T> = Promise<T> | T;
const expect = async <T>(cb: Result<T>): Promise<Expect<T>> => {
try {
return { result: await cb, error: null };
} catch (error) {
if (error instanceof Error) {
return { result: null, error: error };
}
return { result: null, error: new Error(`${error}`) };
}
};
@maddsua
Copy link
Author

maddsua commented Feb 26, 2025

Usage example:

const result = await expect(fetch('google.com'));
if (result.error) {
  // handle error
}

const { result: response } = result;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment