forked from a-synchronous/rubico
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tryCatch.js
47 lines (45 loc) · 1.22 KB
/
tryCatch.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
42
43
44
45
46
47
const isPromise = require('./_internal/isPromise')
const __ = require('./_internal/placeholder')
const curry3 = require('./_internal/curry3')
const catcherApply = require('./_internal/catcherApply')
/**
* @name tryCatch
*
* @synopsis
* ```coffeescript [specscript]
* var args ...any,
* tryer ...args=>Promise|any,
* catcher (error Error, ...args)=>Promise|any
*
* tryCatch(tryer, catcher)(...args) -> Promise|any
* ```
*
* @description
* Try a `tryer`, catch with `catcher`. On error or rejected promise, call the `catcher` with the error followed by any arguments to the tryer.
*
* ```javascript [playground]
* const errorThrower = tryCatch(
* message => {
* throw new Error(message)
* },
* (err, message) => {
* console.log(err)
* return `${message} from catcher`
* },
* )
*
* console.log(errorThrower('hello')) // Error: hello
* // hello from catcher
* ```
*/
const tryCatch = (tryer, catcher) => function tryCatcher(...args) {
try {
const result = tryer(...args)
return isPromise(result)
? result.catch(curry3(catcherApply, catcher, __, args))
: result
} catch (err) {
return catcher(err, ...args)
}
}
module.exports = tryCatch