@@ -8,6 +8,27 @@ export const JSONError = errorEx('JSONError', {
8
8
codeFrame : errorEx . append ( '\n\n%s\n' ) ,
9
9
} ) ;
10
10
11
+ const generateCodeFrame = ( string , location , highlightCode = true ) =>
12
+ codeFrameColumns ( string , { start : location } , { highlightCode} ) ;
13
+
14
+ const getErrorLocation = ( string , error ) => {
15
+ const match = error . message . match ( / i n J S O N a t p o s i t i o n (?< index > \d + ) (?: \( l i n e (?< line > \d + ) c o l u m n (?< column > \d + ) \) ) ? w h i l e p a r s i n g / ) ;
16
+
17
+ if ( ! match ) {
18
+ return ;
19
+ }
20
+
21
+ let { index, line, column} = match . groups ;
22
+
23
+ if ( line && column ) {
24
+ return { line : Number ( line ) , column : Number ( column ) } ;
25
+ }
26
+
27
+ ( { line, column} = new LinesAndColumns ( string ) . locationForIndex ( Number ( index ) ) ) ;
28
+
29
+ return { line : line + 1 , column : column + 1 } ;
30
+ } ;
31
+
11
32
export default function parseJson ( string , reviver , filename ) {
12
33
if ( typeof reviver === 'string' ) {
13
34
filename = reviver ;
@@ -23,26 +44,17 @@ export default function parseJson(string, reviver, filename) {
23
44
}
24
45
} catch ( error ) {
25
46
error . message = error . message . replace ( / \n / g, '' ) ;
26
- const indexMatch = error . message . match ( / i n J S O N a t p o s i t i o n ( \d + ) w h i l e p a r s i n g / ) ;
27
47
28
48
const jsonError = new JSONError ( error ) ;
49
+
29
50
if ( filename ) {
30
51
jsonError . fileName = filename ;
31
52
}
32
53
33
- if ( indexMatch && indexMatch . length > 0 ) {
34
- const lines = new LinesAndColumns ( string ) ;
35
- const index = Number ( indexMatch [ 1 ] ) ;
36
- const location = lines . locationForIndex ( index ) ;
37
-
38
- const generateCodeFrame = ( { highlightCode} ) => codeFrameColumns (
39
- string ,
40
- { start : { line : location . line + 1 , column : location . column + 1 } } ,
41
- { highlightCode} ,
42
- ) ;
43
-
44
- jsonError . codeFrame = generateCodeFrame ( { highlightCode : true } ) ;
45
- jsonError . rawCodeFrame = generateCodeFrame ( { highlightCode : false } ) ;
54
+ const location = getErrorLocation ( string , error ) ;
55
+ if ( location ) {
56
+ jsonError . codeFrame = generateCodeFrame ( string , location ) ;
57
+ jsonError . rawCodeFrame = generateCodeFrame ( string , location , /* highlightCode */ false ) ;
46
58
}
47
59
48
60
throw jsonError ;
0 commit comments