From d036b3534963dc6f3b5d688df33ea21d049e0543 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 8 Nov 2015 09:53:50 -0800 Subject: [PATCH] tools: enforce `throw new Error()` with lint rule Add linting rule requiring `throw new Error()` over `throw Error()`. PR-URL: https://github.com/nodejs/node/pull/3714 Reviewed-By: Evan Lucas Reviewed-By: Colin Ihrig Reviewed-By: Jeremiah Senkpiel Reviewed-By: James M Snell --- .eslintrc | 2 ++ tools/eslint-rules/new-with-error.js | 36 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 tools/eslint-rules/new-with-error.js diff --git a/.eslintrc b/.eslintrc index 1d14b72abb2bf3..bf3fc3378f2d92 100644 --- a/.eslintrc +++ b/.eslintrc @@ -87,6 +87,8 @@ rules: # Custom rules in tools/eslint-rules require-buffer: 2 + new-with-error: [2, "Error", "RangeError", "TypeError", "SyntaxError", "ReferenceError"] + # Global scoped method and vars globals: diff --git a/tools/eslint-rules/new-with-error.js b/tools/eslint-rules/new-with-error.js new file mode 100644 index 00000000000000..b0f550db2ffa2c --- /dev/null +++ b/tools/eslint-rules/new-with-error.js @@ -0,0 +1,36 @@ +/** + * @fileoverview Require `throw new Error()` rather than `throw Error()` + * @author Rich Trott + */ +'use strict'; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var errorList = context.options.length !== 0 ? context.options : ['Error']; + + return { + 'ThrowStatement': function(node) { + if (node.argument.type === 'CallExpression' && + errorList.indexOf(node.argument.callee.name) !== -1) { + context.report(node, 'Use new keyword when throwing.'); + } + } + }; +}; + +module.exports.schema = { + 'type': 'array', + 'items': [ + { + 'enum': [0, 1, 2] + } + ], + 'additionalItems': { + 'type': 'string' + }, + 'uniqueItems': true +};