-
Notifications
You must be signed in to change notification settings - Fork 4
/
error.js
41 lines (36 loc) · 1.2 KB
/
error.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const rethrowError = (error) => {
console.warn(error)
throw error
}
const tryCall = (thisArg, name, ...args) => {
try {
return thisArg[ name ](...args)
} catch (error) { __DEV__ && console.log('[tryCall] failed:', name, error) }
}
// for better flow control
const catchSync = (func, ...args) => {
let result, resultError
try { result = func(...args) } catch (error) { resultError = error || new Error() }
return { result, error: resultError }
}
const catchAsync = async (func, ...args) => {
let result, resultError
try { result = await func(...args) } catch (error) { resultError = error || new Error() }
return { result, error: resultError }
}
// const catchAsync = (func, ...args) => { // NOTE: reference async-less implementation
// try {
// const possiblePromise = func(...args)
// return catchPromise(possiblePromise)
// } catch (error) { return Promise.resolve(packError(error)) }
// }
const catchPromise = (promise) => promise.then(packResult, packError)
const packResult = (result) => ({ result, error: undefined })
const packError = (error) => ({ result: undefined, error: error || new Error() })
export {
rethrowError,
tryCall,
catchSync,
catchAsync,
catchPromise
}