Skip to content

Commit afc566c

Browse files
authored
Merge pull request #470 from prettier/better-errors
Handle better error messages
2 parents e7ad32f + f3f8fcf commit afc566c

File tree

4 files changed

+652
-955
lines changed

4 files changed

+652
-955
lines changed

CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) a
66

77
## [Unreleased]
88

9+
## [2.2.0] - 2022-05-12
10+
11+
### Added
12+
13+
- Better error messages in the case of a syntax error.
14+
915
## [2.1.0] - 2022-04-16
1016

1117
### Added

package.json

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@prettier/plugin-xml",
3-
"version": "2.1.0",
3+
"version": "2.2.0",
44
"description": "prettier plugin for XML",
55
"main": "dist/plugin.js",
66
"scripts": {
@@ -24,15 +24,15 @@
2424
"prettier": ">=2.4.0"
2525
},
2626
"devDependencies": {
27-
"@types/jest": "^27.0.0",
27+
"@types/jest": "^27.5.1",
2828
"@types/node": "^17.0.22",
2929
"@types/prettier": "^2.3.0",
3030
"@typescript-eslint/eslint-plugin": "^5.16.0",
3131
"@typescript-eslint/parser": "^5.16.0",
3232
"eslint": "^8.5.0",
3333
"eslint-config-prettier": "^8.0.0",
34-
"jest": "^27.0.1",
35-
"ts-jest": "^27.0.2",
34+
"jest": "^28.1.0",
35+
"ts-jest": "^28.0.2",
3636
"ts-node": "^10.0.0",
3737
"typescript": "^4.3.2"
3838
},

src/parser.ts

+33-2
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,45 @@
11
import { parse as xmlToolsParse } from "@xml-tools/parser";
22
import type { Parser } from "./types";
33

4+
type LocatedError = Error & {
5+
loc: {
6+
start: { line: number; column: number };
7+
end: { line: number; column: number };
8+
};
9+
};
10+
411
const parser: Parser = {
512
parse(text) {
613
const { lexErrors, parseErrors, cst } = xmlToolsParse(text);
714

8-
if (lexErrors.length > 0 || parseErrors.length > 0) {
9-
throw Error("Error parsing XML");
15+
// If there are any lexical errors, throw the first of them as an error.
16+
if (lexErrors.length > 0) {
17+
const lexError = lexErrors[0];
18+
const error = new Error(lexError.message) as LocatedError;
19+
20+
error.loc = {
21+
start: { line: lexError.line, column: lexError.column },
22+
end: { line: lexError.line, column: lexError.column + lexError.length }
23+
};
24+
25+
throw error;
26+
}
27+
28+
// If there are any parse errors, throw the first of them as an error.
29+
if (parseErrors.length > 0) {
30+
const parseError = parseErrors[0];
31+
const error = new Error(parseError.message) as LocatedError;
32+
33+
const { token } = parseError;
34+
error.loc = {
35+
start: { line: token.startLine!, column: token.startColumn! },
36+
end: { line: token.endLine!, column: token.endColumn! }
37+
};
38+
39+
throw error;
1040
}
1141

42+
// Otherwise return the CST.
1243
return cst;
1344
},
1445
astFormat: "xml",

0 commit comments

Comments
 (0)