summaryrefslogtreecommitdiff
path: root/packages/astro-parser/src/utils/error.ts
blob: bb71db1c7ffb30380eed71774ac8b509675683f9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// @ts-nocheck

import { locate } from 'locate-character';
import get_code_frame from './get_code_frame.js';

export class CompileError extends Error {
	code: string;
	end: { line: number; column: number };
	filename: string;
	frame: string;
	start: { line: number; column: number };

	constructor({ code, filename, start, end, message }: { code: string; filename: string; start: number; message: string; end?: number }) {
		super(message);

		this.start = locate(code, start, { offsetLine: 1 });
		this.end = locate(code, end || start, { offsetLine: 1 });
		this.filename = filename;
		this.message = message;
		this.frame = get_code_frame(code, this.start.line - 1, this.start.column);
	}

	toString() {
		return `${this.filename}:${this.start.line}:${this.start.column}\n\t${this.message}\n${this.frame}`;
	}
}

/** Throw CompileError */
export default function error(
	code: string,
	message: string,
	props: {
		name: string;
		source: string;
		filename: string;
		start: number;
		end?: number;
	}
): never {
	const err = new CompileError({ code, message, start: props.start, end: props.end, filename: props.filename });
	err.name = props.name;

	throw err;
}