Improve context for errors thrown by compiler

This commit introduces a custom error object to provide additional
context for errors throwing during parsing and compiling operations,
improving troubleshooting.

By integrating error context handling, the error messages become more
informative and user-friendly, providing sequence of trace with context
to aid in troubleshooting.

Changes include:

- Introduce custom error object that extends errors with contextual
  information. This replaces previous usages of `AggregateError` which
  is not displayed well by browsers when logged.
- Improve parsing functions to encapsulate error context with more
  details.
- Increase unit test coverage and refactor the related code to be more
  testable.
This commit is contained in:
undergroundwires
2024-05-25 13:55:30 +02:00
parent 7794846185
commit 4212c7b9e0
78 changed files with 3346 additions and 1268 deletions

View File

@@ -0,0 +1,67 @@
import type { ErrorWithContextWrapper } from '@/application/Parser/ContextualError';
export class ErrorWrapperStub {
private errorToReturn: Error | undefined;
private parameters?: Parameters<ErrorWithContextWrapper>;
public get lastError(): Error | undefined {
if (!this.parameters) {
return undefined;
}
return getError(this.parameters);
}
public get lastContext(): string | undefined {
if (!this.parameters) {
return undefined;
}
return getAdditionalContext(this.parameters);
}
public withError(error: Error): this {
this.errorToReturn = error;
return this;
}
public get(): ErrorWithContextWrapper {
return (...args) => {
this.parameters = args;
if (this.errorToReturn) {
return this.errorToReturn;
}
return new Error(
`[${ErrorWrapperStub.name}] Error wrapped with additional context.`
+ `\nAdditional context: ${getAdditionalContext(args)}`
+ `\nWrapped error message: ${getError(args).message}`
+ `\nWrapped error stack trace:\n${getLimitedStackTrace(getError(args), 5)}`,
);
};
}
}
function getAdditionalContext(
parameters: Parameters<ErrorWithContextWrapper>,
): string {
return parameters[1];
}
function getError(
parameters: Parameters<ErrorWithContextWrapper>,
): Error {
return parameters[0];
}
function getLimitedStackTrace(
error: Error,
limit: number,
): string {
const { stack } = error;
if (!stack) {
return 'No stack trace available';
}
return stack
.split('\n')
.slice(0, limit + 1)
.join('\n');
}