|
Last change
on this file was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago |
|
Added visualizations
|
-
Property mode
set to
100644
|
|
File size:
1.2 KB
|
| Line | |
|---|
| 1 | /**
|
|---|
| 2 | * Attempts to execute a function with the provided arguments.
|
|---|
| 3 | * If the function throws an error, it catches the error and returns it.
|
|---|
| 4 | * If the caught error is not an instance of Error, it wraps it in a new Error.
|
|---|
| 5 | *
|
|---|
| 6 | * @param {(...args: any[]) => R} func - The function to be executed.
|
|---|
| 7 | * @param {...any[]} args - The arguments to pass to the function.
|
|---|
| 8 | * @returns {R | Error} The return value of the function if successful, or an Error if an exception is thrown.
|
|---|
| 9 | *
|
|---|
| 10 | * @template R - The type of the function return value.
|
|---|
| 11 | *
|
|---|
| 12 | * @example
|
|---|
| 13 | * // Example 1: Successful execution
|
|---|
| 14 | * const result = attempt((x, y) => x + y, 2, 3);
|
|---|
| 15 | * console.log(result); // Output: 5
|
|---|
| 16 | *
|
|---|
| 17 | * @example
|
|---|
| 18 | * // Example 2: Function throws an error
|
|---|
| 19 | * const errorResult = attempt(() => {
|
|---|
| 20 | * throw new Error("Something went wrong");
|
|---|
| 21 | * });
|
|---|
| 22 | * console.log(errorResult); // Output: Error: Something went wrong
|
|---|
| 23 | *
|
|---|
| 24 | * @example
|
|---|
| 25 | * // Example 3: Non-Error thrown
|
|---|
| 26 | * const nonErrorResult = attempt(() => {
|
|---|
| 27 | * throw "This is a string error";
|
|---|
| 28 | * });
|
|---|
| 29 | * console.log(nonErrorResult); // Output: Error: This is a string error
|
|---|
| 30 | */
|
|---|
| 31 | declare function attempt<R>(func: (...args: any[]) => R, ...args: any[]): R | Error;
|
|---|
| 32 |
|
|---|
| 33 | export { attempt };
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.