# attempt
# Description
调用传入的 func , 返回结果或者返回捕获到的错误
# Params
(func, ...args)
{Function} func: function
{...*} [args]: func 调用的参数
# Return
func 的执行结果或者 Error
# Depend
import isError from './isError.js'
# Code
function attempt(func, ...args) {
try {
return func(...args)
} catch (e) {
return isError(e) ? e : new Error(e)
}
}
# Analyze
- 使用
try catch进行错误处理 - 如果
func执行正常,则返回结果,否则进入catch - 如果
catch为Error,则返回error, 否则返回new Error
# Remark
使用 try catch 处理有可能的 func 的报错,并且使用 ...args 处理了参数的传递
# Example
const a = attempt((x) => {JSON.parse(x)}, '33.')
a // Error
const b = attempt((x) => {JSON.parse(x)}, '{“a”: “1”}')
b // {a: 1}