Get type safe exceptions from acorn [closed]

3 weeks ago 16
ARTICLE AD BOX

Here is my code

import {parseExpressionAt} from "acorn" interface AcornSyntaxError extends SyntaxError { pos: number; raisedAt: number; loc?: { line: number; column: number; }; } function is_acorn_error(e: unknown):e is AcornSyntaxError { return ( e instanceof SyntaxError && typeof (e as AcornSyntaxError).raisedAt === "number" ); } function parse_test(){ try{ const source=`{"foo: "hellw"}` //source has deliberastly syntax error to test the is_acorn_error function const ast = parseExpressionAt(source, 0, { ecmaVersion: "latest", }) console.log(ast) }catch(ex){ if (is_acorn_error(ex)){ console.log('is_acorn_error',ex.raisedAt) }else{ console.log('not acorn error') } } } parse_test()

output is

is_acorn_error 13

The goal is to get type safe exceptions from acorn.

My question is: it does works fine for me. But:

Is this best practice? Why isn't there similar code in the acorn library itself?
Read Entire Article