Skip to content

Commit

Permalink
Add rawCodeFrame property to JSONError (#37)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
crondinini and sindresorhus committed Sep 1, 2023
1 parent 258f831 commit 9f3bd0b
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 5 deletions.
9 changes: 7 additions & 2 deletions index.d.ts
Expand Up @@ -3,7 +3,7 @@ import type {JsonObject} from 'type-fest';
/**
Exposed for `instanceof` checking.
*/
export type JSONError = Error & { // eslint-disable-line @typescript-eslint/naming-convention
export class JSONError extends Error { // eslint-disable-line @typescript-eslint/naming-convention
/**
The filename displayed in the error message, if any.
*/
Expand All @@ -13,7 +13,12 @@ export type JSONError = Error & { // eslint-disable-line @typescript-eslint/nami
The printable section of the JSON which produces the error.
*/
readonly codeFrame: string;
};

/**
The raw version of `codeFrame` without colors.
*/
readonly rawCodeFrame: string;
}

// Get 'reviver' parameter from JSON.parse()
type ReviverFn = Parameters<typeof JSON['parse']>['1'];
Expand Down
7 changes: 4 additions & 3 deletions index.js
Expand Up @@ -35,13 +35,14 @@ export default function parseJson(string, reviver, filename) {
const index = Number(indexMatch[1]);
const location = lines.locationForIndex(index);

const codeFrame = codeFrameColumns(
const generateCodeFrame = ({highlightCode}) => codeFrameColumns(
string,
{start: {line: location.line + 1, column: location.column + 1}},
{highlightCode: true},
{highlightCode},
);

jsonError.codeFrame = codeFrame;
jsonError.codeFrame = generateCodeFrame({highlightCode: true});
jsonError.rawCodeFrame = generateCodeFrame({highlightCode: false});
}

throw jsonError;
Expand Down
6 changes: 6 additions & 0 deletions index.test-d.ts
Expand Up @@ -33,6 +33,12 @@ const jsonError: JSONError = {
> 3 | }
| ^
`,
rawCodeFrame: `
1 | {
2 | "foo": true,
> 3 | }
| ^
`,
};

expectError(jsonError.codeFrame = '');
6 changes: 6 additions & 0 deletions readme.md
Expand Up @@ -105,3 +105,9 @@ The filename displayed in the error message.
Type: `string`

The printable section of the JSON which produces the error.

#### rawCodeFrame

Type: `string`

The raw version of `codeFrame` without colors.
9 changes: 9 additions & 0 deletions test.js
Expand Up @@ -49,3 +49,12 @@ test('throws exported error error', t => {
instanceOf: JSONError,
});
});

test('has error frame properties', t => {
try {
parseJson('{\n\t"foo": true,\n}', 'foo.json');
} catch (error) {
t.assert(error.codeFrame);
t.is(error.rawCodeFrame, ' 1 | {\n 2 | \t"foo": true,\n> 3 | }\n | ^');
}
});

0 comments on commit 9f3bd0b

Please sign in to comment.