/** тип async function */
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor

/**
 * Безопасный запуск востановителя
 * @param {(...errs: Error[]) => void} restorer
 */
const start_restorer = (restorer) => (...errs) => {
    try {
        return restorer(...errs)
    } catch (e) {
        console.error(e)
        throw e
    }
}

/**
 * Функция отлова исключений
 * @param {(...args: any[]) => any} func 
 * @param {(...errs: Error[]) => void} restorer
 * @returns {(...args: any[]) => any}
 */
const recovery = (func, restorer = (...args) => {throw new Error(...args)}) => {
    let resFunc
    if(func instanceof AsyncFunction)
        resFunc = async (...args) => {
            try {return await func(...args)}
            catch (e) {return start_restorer(restorer)(e)}
        }
    else
        resFunc = (...args) => {
            try {return func(...args)}
            catch (e) {return start_restorer(restorer)(e)}
        }
    return resFunc
}
