From e5fd213d6b2e906e2b8db90fd21fce1c615b74a2 Mon Sep 17 00:00:00 2001 From: cxtom Date: Wed, 10 Jul 2019 13:40:49 +0800 Subject: [PATCH] feat: support error property --- src/features/error.ts | 40 +++++++++++++++++++++++++++++++++++++ src/features/index.ts | 4 +++- test/features/exception.php | 2 +- test/features/exception.ts | 2 +- 4 files changed, 45 insertions(+), 3 deletions(-) create mode 100644 src/features/error.ts diff --git a/src/features/error.ts b/src/features/error.ts new file mode 100644 index 0000000..80c885b --- /dev/null +++ b/src/features/error.ts @@ -0,0 +1,40 @@ +/** + * @file Exception + * @author cxtom(cxtom2008@gmail.com) + */ + +import * as ts from 'typescript'; + +const map = { + message: 'getMessage', + lineNumber: 'getLine', + file: 'getFile', + stack: 'getTraceAsString' +}; + +export default { + + emit(hint, node, {helpers, typeChecker}) { + + const { + getTextOfNode, + emitExpression, + writeBase + } = helpers; + + if ( + ts.isPropertyAccessExpression(node) + && ts.isIdentifier(node.name) + && map[getTextOfNode(node.name)] + ) { + const symbol = typeChecker.getSymbolAtLocation(node.expression); + const declaration = symbol.valueDeclaration; + if (declaration && ts.isCatchClause(declaration.parent)) { + emitExpression(node.expression); + return writeBase(`->${map[getTextOfNode(node.name)]}()`); + } + } + + return false; + } +}; diff --git a/src/features/index.ts b/src/features/index.ts index faac13a..acbba11 100644 --- a/src/features/index.ts +++ b/src/features/index.ts @@ -12,6 +12,7 @@ import NumberPlugin from './number'; import ArrayPlugin from './array'; import ConsolePlugin from './console'; import DatePlugin from './date'; +import ErrorPlugin from './error'; export default [ StringPligin, @@ -22,5 +23,6 @@ export default [ NumberPlugin, ArrayPlugin, ConsolePlugin, - DatePlugin + DatePlugin, + ErrorPlugin ]; diff --git a/test/features/exception.php b/test/features/exception.php index e7e59f9..aee82cf 100644 --- a/test/features/exception.php +++ b/test/features/exception.php @@ -4,7 +4,7 @@ throw new \Exception("error!"); } catch (\Exception $e) { - echo "error"; + echo "error" . $e->getMessage(); } $a = "hard"; throw new \Exception("a " . $a . " error!"); diff --git a/test/features/exception.ts b/test/features/exception.ts index 69f0dda..9bfe9ee 100644 --- a/test/features/exception.ts +++ b/test/features/exception.ts @@ -3,7 +3,7 @@ try { throw 'error!'; } catch (e) { - console.log('error'); + console.log('error' + e.message); } const a = 'hard';