escodegen
escodegen copied to clipboard
Better Errors
I'm working on a project where it generates AST based on an external data source (specification -> js ast -> js code). I get errors like this:
TypeError: Cannot read property 'type' of undefined
at generateStatement (/.../my-project/node_modules/escodegen/escodegen.js:1557:21)
at /.../my-project/node_modules/escodegen/escodegen.js:1563:42
at withIndent (/.../my-project/node_modules/escodegen/escodegen.js:564:21)
at generateStatement (/.../my-project/node_modules/escodegen/escodegen.js:1561:13)
at maybeBlock (/.../my-project/node_modules/escodegen/escodegen.js:717:28)
at generateFunctionBody (/.../my-project/node_modules/escodegen/escodegen.js:826:25)
at generateExpression (/.../my-project/node_modules/escodegen/escodegen.js:1195:27)
at generateExpression (/.../my-project/node_modules/escodegen/escodegen.js:918:21)
at generateStatement (/.../my-project/node_modules/escodegen/escodegen.js:1661:23)
at generateStatement (/.../my-project/node_modules/escodegen/escodegen.js:1955:21)
It'd be good to include some kind of message explaining where the error is. This could be done with a recursive stack. When you recurse, push the key onto the stack (e.g. "0" or "expression"). When you exit a level of recursion, pop an item from the stack.
If the code is wrapped in a try/catch, you can then look at the stack and console.log("Error at " + stack.join('.'))
, and rethrow the error.
Now the error would look like this, which I can resolve by hand or with an extract function.
Error at 0.body.body.0.left
TypeError: Cannot read property 'type' of undefined
at generateStatement (/.../my-project/node_modules/escodegen/escodegen.js:1557:21)