-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexc.mjs
45 lines (40 loc) · 1 KB
/
exc.mjs
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
import { toStr } from "./fmt.mjs"
const Exc = ({ name, msg, ...a }) => {
const exc = Error(toStr(msg || ""))
exc.name = name
for (const [k, v] of Object.entries(a)) exc[k] = v
return exc
}
const isExcWrappedBy = p => ws => e =>
ws.some(w => (!w && p(e)) || (e.name === w && p(e.cause)))
const logExc =
L =>
(...ss) => {
let async_ = async (th, { rethrow = true, logExc = true } = {}) => {
try {
return await th()
} catch (e) {
if (ss.length) await L.nat.san(...ss)
if (logExc) await L.exc.san(e)
if (rethrow) throw e
}
}
async_.asyncGen = async function* (
th,
{ rethrow = true, logExc = true } = {}
) {
try {
yield* th()
} catch (e) {
if (ss.length) await L.nat.san(...ss)
if (logExc) await L.exc.san(e)
if (rethrow) throw e
}
}
return async_
}
const logFailed =
L =>
(...ss) =>
logExc(L)(...[...ss, "failed"])
export { Exc, logExc, logFailed, isExcWrappedBy }