wiki/quartz/util/trace.ts

44 lines
944 B
TypeScript
Raw Permalink Normal View History

import chalk from "chalk"
import process from "process"
import { isMainThread } from "workerpool"
const rootFile = /.*at file:/
export function trace(msg: string, err: Error) {
let stack = err.stack ?? ""
const lines: string[] = []
lines.push("")
lines.push(
"\n" +
2023-08-09 05:53:01 +00:00
chalk.bgRed.black.bold(" ERROR ") +
"\n\n" +
2023-08-09 05:53:01 +00:00
chalk.red(` ${msg}`) +
(err.message.length > 0 ? `: ${err.message}` : ""),
2023-07-23 00:27:41 +00:00
)
let reachedEndOfLegibleTrace = false
2023-07-23 00:27:41 +00:00
for (const line of stack.split("\n").slice(1)) {
if (reachedEndOfLegibleTrace) {
break
}
if (!line.includes("node_modules")) {
lines.push(` ${line}`)
if (rootFile.test(line)) {
reachedEndOfLegibleTrace = true
}
}
}
const traceMsg = lines.join("\n")
if (!isMainThread) {
// gather lines and throw
throw new Error(traceMsg)
} else {
// print and exit
console.error(traceMsg)
process.exit(1)
}
}