diff --git a/README.md b/README.md index ce5f7a8..ba10722 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,41 @@ async function completeApplicationFlow() { jscodeshift -t transforms/async-await-with-try-catch.js ``` +If you want to replace the default `console.log(e)` with your custom function call for example `error.handleError(e)`, +you can pass that as an option `--catchBlock` + +```sh +jscodeshift -t transforms/async-await-with-try-catch.js --catchBlock=error.handleError +``` + +This will transform your code to:- + +```javascript +async function completeApplicationFlow() { + // wait for get session status api to check the status + let response; + try { + response = await getSessionStatusApi(); + } catch(e) { + error.handleError(e) + } + // wait for getting next set of questions api + try { + response = await getNextQuestionsApi(); + } catch(e) { + error.handleError(e) + } + // finally submit application + try { + response = await submitApplication(); + } catch(e) { + error.handleError(e) + } +} + +``` + + ### Recast Options Options to [recast](https://github.com/benjamn/recast)'s printer can be provided diff --git a/transforms/async-await-with-try-catch.js b/transforms/async-await-with-try-catch.js index 151b04f..ec1fcf7 100644 --- a/transforms/async-await-with-try-catch.js +++ b/transforms/async-await-with-try-catch.js @@ -1,10 +1,25 @@ -// Press ctrl+space for code completion - -export default function transformer(file, api) { +export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); + const ExpressionTypes = ['BinaryExpression', 'LogicalExpression', 'NewExpression', 'ObjectExpression']; const DisAllowedFunctionExpressionTypes = ['ArrowFunctionExpression', 'FunctionExpression', 'ObjectExpression']; + + function getCatchBlockExpression() { + if(options.catchBlock) { + const [obj, property] = options.catchBlock.split('.'); + if(property) { + return j.callExpression(j.memberExpression(j.identifier(obj), j.identifier(property)), [ + j.identifier('e') + ]); + } else { + return j.callExpression(j.identifier(obj), [ + j.identifier('e') + ]); + } + } + return j.callExpression(j.memberExpression(j.identifier('console'), j.identifier('log')), [j.identifier('e')]); + } function isAlreadyInsideTryBlock(path) { return j(path).closest(j.TryStatement).length; } @@ -13,15 +28,7 @@ export default function transformer(file, api) { j(path).replaceWith( j.tryStatement( j.blockStatement([type]), - j.catchClause( - j.identifier('e'), - null, - j.blockStatement([ - j.expressionStatement( - j.callExpression(j.memberExpression(j.identifier('console'), j.identifier('log')), [j.identifier('e')]) - ) - ]) - ) + j.catchClause(j.identifier('e'), null, j.blockStatement([j.expressionStatement(getCatchBlockExpression())])) ) ); }