Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add raw codeFrame and fix JSONError type #37

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions index.d.ts
Original file line number Diff line number Diff line change
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,7 @@ export type JSONError = Error & { // eslint-disable-line @typescript-eslint/nami
The printable section of the JSON which produces the error.
*/
readonly codeFrame: string;
};
}

// Get 'reviver' parameter from JSON.parse()
type ReviverFn = Parameters<typeof JSON['parse']>['1'];
Expand Down
7 changes: 4 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
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
9 changes: 9 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
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.true(error.rawCodeFrame === ' 1 | {\n 2 | \t"foo": true,\n> 3 | }\n | ^');
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use t.is()

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

}
});