@opra/common
Version:
Opra common package
66 lines (65 loc) • 1.77 kB
JavaScript
import { OpraDocumentError } from './opra-document-error.js';
export class DocumentInitContext {
constructor(options) {
this.path = '';
this.error = new OpraDocumentError();
this.showErrorDetails = true;
this.maxErrors = options?.maxErrors || 0;
this.error.message = '';
}
addError(error) {
if (!this.error.details.length) {
if (error instanceof Error)
this.error.stack = error.stack;
else {
const e = new Error();
Error.captureStackTrace(e, this.addError);
this.error.stack = e.stack;
}
}
// @ts-ignore
this.error.add({
message: typeof error === 'string' ? error : error.message,
path: this.path,
...(typeof error === 'object' ? error : undefined),
});
if (this.error.details.length >= this.maxErrors)
throw this.error;
}
enter(path, fn) {
const oldPath = this.path;
this.path = this.path + path;
try {
return fn();
}
catch (e) {
if (e !== this.error) {
this.addError(e);
}
}
finally {
this.path = oldPath;
}
}
async enterAsync(path, fn) {
const oldPath = this.path;
this.path = this.path + path;
try {
return await fn();
}
catch (e) {
if (e !== this.error)
this.addError(e);
}
finally {
this.path = oldPath;
}
}
extend(args) {
const out = {
...args,
};
Object.setPrototypeOf(out, this);
return out;
}
}