This function provides a structured way to handle asynchronous operations that may either succeed or fail, returning a `Result` type that encapsulates the outcome.
npm install @jsts-utils/trycatchtryCatch FunctionThis function provides a structured way to handle asynchronous operations that may either succeed or fail, returning a Result type that encapsulates the outcome.
``typescript`
export async function tryCatch
promise: Promise
): PromisetryCatchDescription
The function takes a Promise as input and attempts to resolve it. If the promise resolves successfully, it returns a Success object containing the resolved value and null for the error. If the promise rejects, it catches the error and returns a Failure object containing null for the response and the caught error.Result$3
The function returns a type, which is a discriminated union of Success and Failure.
`typescript
type Success
response: T;
error: null;
};
type Failure
response: null;
error: E;
};
type Result
`Success
- : Represents a successful operation, where T is the type of the resolved value.Failure
- : Represents a failed operation, where E is the type of the error. The default error type is Error.
typescript
async function main() {
const getPost = fetch('https://jsonplaceholder.typicode.com/todos/1')
// const result = await tryCatch(getPost); or
const {response, error} = await tryCatch(getPost);
if(error !== null) return error;
const data = await response.json()
console.log(data)
}main();
`Benefits
- Provides a consistent and type-safe way to handle asynchronous results.
- Eliminates the need for repetitive
try...catch` blocks.