@@ -5,38 +5,54 @@ export interface TryCatchError extends Error {
55}
66
77export class TryCatchError extends Error implements TryCatchError {
8- constructor ( error : Error ) { // esline-disable-error
9- super ( error . name )
8+ constructor ( error : Error ) {
9+ super ( error . name ) ;
1010
11- this . name = error . name
12- this . message = error . message
13- this . stack = error . stack
11+ this . name = error . name ;
12+ this . message = error . message ;
13+ this . stack = error . stack ;
1414 }
1515}
1616
17- export async function tryCatch < T > (
18- subject : Function | Promise < T > ,
17+ type TryCatchReturnType < ReturnType > =
18+ | [ TryCatchError , undefined ]
19+ | [ null , ReturnType ] ;
20+
21+ export function tryCatch < ReturnType > (
22+ subject : Promise < ReturnType >
23+ ) : Promise < TryCatchReturnType < ReturnType > > ;
24+ export function tryCatch < ReturnType > (
25+ subject : ( ..._args : any [ ] ) => ReturnType
26+ ) : Promise < TryCatchReturnType < ReturnType > > ;
27+ export function tryCatch < ReturnType > (
28+ subject : ( ..._args : Promise < any > [ ] ) => Promise < ReturnType >
29+ ) : Promise < TryCatchReturnType < ReturnType > > ;
30+ export async function tryCatch < ReturnType > (
31+ subject :
32+ | Promise < ReturnType >
33+ | ( ( ..._args : any [ ] ) => ReturnType )
34+ | ( ( ..._args : Promise < any > [ ] ) => Promise < ReturnType > ) ,
1935 ...args : any [ ]
20- ) : Promise < [ TryCatchError , undefined ] | [ null , T ] > {
36+ ) : Promise < TryCatchReturnType < ReturnType > > {
2137 if ( typeof subject === 'function' ) {
22- const fn = ( subject as typeof subject )
38+ const fn = subject as typeof subject ;
2339
2440 try {
25- return [ null , await fn ( ...args ) ]
41+ return [ null , await fn ( ...args ) ] ;
2642 } catch ( error ) {
27- return [ new TryCatchError ( error ) , undefined ]
43+ return [ new TryCatchError ( error ) , undefined ] ;
2844 }
2945 }
3046
3147 if ( Promise . resolve ( subject ) === subject ) {
3248 try {
33- return [ null , await subject ]
49+ return [ null , await subject ] ;
3450 } catch ( error ) {
35- return [ new TryCatchError ( error ) , undefined ]
51+ return [ new TryCatchError ( error ) , undefined ] ;
3652 }
3753 }
3854
39- return [ new TypeError ( `' ${ subject ? subject . toString ( ) : subject } ' is not a function or promise` ) , undefined ]
55+ return [ new TypeError ( `Subject is not a function or promise` ) , undefined ] ;
4056}
4157
42- export default tryCatch
58+ export default tryCatch ;
0 commit comments