123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- "use strict";
- const astUtils = require("./utils/ast-utils");
- module.exports = {
- meta: {
- type: "suggestion",
- docs: {
- description: "Require using Error objects as Promise rejection reasons",
- recommended: false,
- url: "https://eslint.org/docs/latest/rules/prefer-promise-reject-errors"
- },
- fixable: null,
- schema: [
- {
- type: "object",
- properties: {
- allowEmptyReject: { type: "boolean", default: false }
- },
- additionalProperties: false
- }
- ],
- messages: {
- rejectAnError: "Expected the Promise rejection reason to be an Error."
- }
- },
- create(context) {
- const ALLOW_EMPTY_REJECT = context.options.length && context.options[0].allowEmptyReject;
- const sourceCode = context.sourceCode;
-
-
-
-
- function checkRejectCall(callExpression) {
- if (!callExpression.arguments.length && ALLOW_EMPTY_REJECT) {
- return;
- }
- if (
- !callExpression.arguments.length ||
- !astUtils.couldBeError(callExpression.arguments[0]) ||
- callExpression.arguments[0].type === "Identifier" && callExpression.arguments[0].name === "undefined"
- ) {
- context.report({
- node: callExpression,
- messageId: "rejectAnError"
- });
- }
- }
-
- function isPromiseRejectCall(node) {
- return astUtils.isSpecificMemberAccess(node.callee, "Promise", "reject");
- }
-
-
-
- return {
-
- CallExpression(node) {
- if (isPromiseRejectCall(node)) {
- checkRejectCall(node);
- }
- },
-
- "NewExpression:exit"(node) {
- if (
- node.callee.type === "Identifier" && node.callee.name === "Promise" &&
- node.arguments.length && astUtils.isFunction(node.arguments[0]) &&
- node.arguments[0].params.length > 1 && node.arguments[0].params[1].type === "Identifier"
- ) {
- sourceCode.getDeclaredVariables(node.arguments[0])
-
- .find(variable => variable.name === node.arguments[0].params[1].name)
-
- .references
-
- .filter(ref => ref.isRead())
-
- .filter(ref => ref.identifier.parent.type === "CallExpression" && ref.identifier === ref.identifier.parent.callee)
-
- .forEach(ref => checkRejectCall(ref.identifier.parent));
- }
- }
- };
- }
- };
|