Skip to content

Commit

Permalink
feat: support report error cause (#308)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <[email protected]>
  • Loading branch information
kongmoumou and pi0 authored Dec 19, 2024
1 parent e510121 commit 699d890
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 5 deletions.
13 changes: 13 additions & 0 deletions examples/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { consola } from "./utils";

const error = new Error("This is an error", {
cause: new Error("This is the cause", {
cause: new Error("This is the cause of the cause"),
}),
});

console.error(error);

console.log("\n");

consola.error(error);
18 changes: 16 additions & 2 deletions src/reporters/basic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,27 @@ const bracket = (x: string) => (x ? `[${x}]` : "");

export class BasicReporter implements ConsolaReporter {
formatStack(stack: string, opts: FormatOptions) {
return " " + parseStack(stack).join("\n ");
const indent = " ".repeat((opts?.errorLevel || 0) + 1);
return indent + parseStack(stack).join(`\n${indent}`);
}

formatError(err: any, opts: FormatOptions): string {
const message = err.message ?? formatWithOptions(opts, err);
const stack = err.stack ? this.formatStack(err.stack, opts) : "";

const level = opts?.errorLevel || 0;
const causedPrefix = level > 0 ? `${" ".repeat(level)}[cause]: ` : "";
const causedError = err.cause
? "\n\n" + this.formatError(err.cause, { ...opts, errorLevel: level + 1 })
: "";

return causedPrefix + message + "\n" + stack + causedError;
}

formatArgs(args: any[], opts: FormatOptions) {
const _args = args.map((arg) => {
if (arg && typeof arg.stack === "string") {
return arg.message + "\n" + this.formatStack(arg.stack, opts);
return this.formatError(arg, opts);
}
return arg;
});
Expand Down
7 changes: 4 additions & 3 deletions src/reporters/fancy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,10 @@ function stringWidth(str: string) {
}

export class FancyReporter extends BasicReporter {
formatStack(stack: string) {
formatStack(stack: string, opts: FormatOptions) {
const indent = " ".repeat((opts?.errorLevel || 0) + 1);
return (
"\n" +
`\n${indent}` +
parseStack(stack)
.map(
(line) =>
Expand All @@ -57,7 +58,7 @@ export class FancyReporter extends BasicReporter {
.replace(/^at +/, (m) => colors.gray(m))
.replace(/\((.+)\)/, (_, m) => `(${colors.cyan(m)})`),
)
.join("\n")
.join(`\n${indent}`)
);
}

Expand Down
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ export interface FormatOptions {
*/
compact?: boolean | number;

/**
* Error cause level.
*/
errorLevel?: number;

/**
* Allows additional custom formatting options.
*/
Expand Down

0 comments on commit 699d890

Please sign in to comment.