-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #89 from noelforte/error-subclasses
Implement `TransformError`/`TemplateError` subclasses
- Loading branch information
Showing
4 changed files
with
80 additions
and
72 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
class VentoBaseError extends Error { | ||
override name = this.constructor.name; | ||
} | ||
|
||
export class TemplateError extends VentoBaseError { | ||
constructor( | ||
public path: string = "<unknown>", | ||
public source: string = "<empty file>", | ||
public position: number = 0, | ||
cause?: Error, | ||
) { | ||
const { line, column, code } = errorLine(source, position); | ||
super( | ||
`Error in template ${path}:${line}:${column}\n\n${code.trim()}\n\n`, | ||
{ cause }, | ||
); | ||
|
||
if (cause) { | ||
this.message += `(via ${cause.name})\n`; | ||
} | ||
} | ||
} | ||
|
||
export class TransformError extends VentoBaseError { | ||
constructor( | ||
message: string, | ||
public position: number = 0, | ||
cause?: Error, | ||
) { | ||
super(message, { cause }); | ||
} | ||
} | ||
|
||
/** Returns the number and code of the errored line */ | ||
export function errorLine( | ||
source: string, | ||
position: number, | ||
): { line: number; column: number; code: string } { | ||
let line = 1; | ||
let column = 1; | ||
|
||
for (let index = 0; index < position; index++) { | ||
if ( | ||
source[index] === "\n" || | ||
(source[index] === "\r" && source[index + 1] === "\n") | ||
) { | ||
line++; | ||
column = 1; | ||
|
||
if (source[index] === "\r") { | ||
index++; | ||
} | ||
} else { | ||
column++; | ||
} | ||
} | ||
|
||
return { line, column, code: source.split("\n")[line - 1] }; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters