Skip to content

Latest commit

 

History

History
92 lines (63 loc) · 1.78 KB

no-throw-statements.md

File metadata and controls

92 lines (63 loc) · 1.78 KB

Disallow throwing exceptions (functional/no-throw-statements)

💼 This rule is enabled in the following configs: ☑️ lite, no-exceptions, ✅ recommended, 🔒 strict.

This rule disallows the throw keyword.

Rule Details

Exceptions are not part of functional programming. As an alternative a function should return an error or in the case of an async function, a rejected promise.

❌ Incorrect

/* eslint functional/no-throw-statements: "error" */

throw new Error("Something went wrong.");

✅ Correct

/* eslint functional/no-throw-statements: "error" */

function divide(x, y) {
  return y === 0 ? new Error("Cannot divide by zero.") : x / y;
}
/* eslint functional/no-throw-statements: "error" */

async function divide(x, y) {
  const [xv, yv] = await Promise.all([x, y]);

  return yv === 0
    ? Promise.reject(new Error("Cannot divide by zero."))
    : xv / yv;
}

Options

This rule accepts an options object of the following type:

type Options = {
  allowInAsyncFunctions: boolean;
};

Default Options

const defaults = {
  allowInAsyncFunctions: false,
};

Preset Overrides

recommended and lite

const recommendedAndLiteOptions = {
  allowInAsyncFunctions: true,
};

allowInAsyncFunctions

If true, throw statements will be allowed within async functions.
This essentially allows throw statements to be used as return statements for errors.

✅ Correct

/* eslint functional/no-throw-statements: ["error", { "allowInAsyncFunctions": true }] */

async function divide(x, y) {
  const [xv, yv] = await Promise.all([x, y]);

  if (yv === 0) {
    throw new Error("Cannot divide by zero.");
  }
  return xv / yv;
}