Expected the promise rejection reason to be an error

Name already in use archive-website / docs / rules / prefer-promise-reject-errors.md Go to file T Go to line L Copy path Copy permalink Copy raw contents Copy raw contents Requires using Error objects as Promise rejection reasons. It is considered good practice to only pass instances of the built-in Error object to the reject() […]

Содержание

  1. Name already in use
  2. archive-website / docs / rules / prefer-promise-reject-errors.md
  3. Name already in use
  4. eslint.github.io / docs / rules / prefer-promise-reject-errors.md
  5. Name already in use
  6. archive-website / docs / 5.0.0 / rules / prefer-promise-reject-errors.md
  7. Name already in use
  8. archive-website / docs / 6.0.0 / rules / prefer-promise-reject-errors.md
  9. prefer-promise-reject-errors
  10. Rule Details
  11. Options
  12. Known Limitations
  13. Когда не использовать его

Name already in use

archive-website / docs / rules / prefer-promise-reject-errors.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

Requires using Error objects as Promise rejection reasons.

It is considered good practice to only pass instances of the built-in Error object to the reject() function for user-defined errors in Promises. Error objects automatically store a stack trace, which can be used to debug an error by determining where it came from. If a Promise is rejected with a non- Error value, it can be difficult to determine where the rejection occurred.

This rule aims to ensure that Promises are only rejected with Error objects.

This rule takes one optional object argument:

  • allowEmptyReject: true ( false by default) allows calls to Promise.reject() with no arguments.

Examples of incorrect code for this rule:

Examples of correct code for this rule:

Examples of correct code for this rule with the allowEmptyReject: true option:

Due to the limits of static analysis, this rule cannot guarantee that you will only reject Promises with Error objects. While the rule will report cases where it can guarantee that the rejection reason is clearly not an Error , it will not report cases where there is uncertainty about whether a given reason is an Error . For more information on this caveat, see the similar limitations in the no-throw-literal rule.

To avoid conflicts between rules, this rule does not report non-error values used in throw statements in async functions, even though these lead to Promise rejections. To lint for these cases, use the no-throw-literal rule.

When Not To Use It

If you’re using custom non-error values as Promise rejection reasons, you can turn off this rule.

Источник

Name already in use

eslint.github.io / docs / rules / prefer-promise-reject-errors.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

require using Error objects as Promise rejection reasons (prefer-promise-reject-errors)

It is considered good practice to only pass instances of the built-in Error object to the reject() function for user-defined errors in Promises. Error objects automatically store a stack trace, which can be used to debug an error by determining where it came from. If a Promise is rejected with a non- Error value, it can be difficult to determine where the rejection occurred.

This rule aims to ensure that Promises are only rejected with Error objects.

This rule takes one optional object argument:

  • allowEmptyReject: true ( false by default) allows calls to Promise.reject() with no arguments.

Examples of incorrect code for this rule:

Examples of correct code for this rule:

Examples of correct code for this rule with the allowEmptyReject: true option:

Due to the limits of static analysis, this rule cannot guarantee that you will only reject Promises with Error objects. While the rule will report cases where it can guarantee that the rejection reason is clearly not an Error , it will not report cases where there is uncertainty about whether a given reason is an Error . For more information on this caveat, see the similar limitations in the no-throw-literal rule.

To avoid conflicts between rules, this rule does not report non-error values used in throw statements in async functions, even though these lead to Promise rejections. To lint for these cases, use the no-throw-literal rule.

When Not To Use It

If you’re using custom non-error values as Promise rejection reasons, you can turn off this rule.

Источник

Name already in use

archive-website / docs / 5.0.0 / rules / prefer-promise-reject-errors.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

require using Error objects as Promise rejection reasons (prefer-promise-reject-errors)

It is considered good practice to only pass instances of the built-in Error object to the reject() function for user-defined errors in Promises. Error objects automatically store a stack trace, which can be used to debug an error by determining where it came from. If a Promise is rejected with a non- Error value, it can be difficult to determine where the rejection occurred.

This rule aims to ensure that Promises are only rejected with Error objects.

This rule takes one optional object argument:

  • allowEmptyReject: true ( false by default) allows calls to Promise.reject() with no arguments.

Examples of incorrect code for this rule:

Examples of correct code for this rule:

Examples of correct code for this rule with the allowEmptyReject: true option:

Due to the limits of static analysis, this rule cannot guarantee that you will only reject Promises with Error objects. While the rule will report cases where it can guarantee that the rejection reason is clearly not an Error , it will not report cases where there is uncertainty about whether a given reason is an Error . For more information on this caveat, see the similar limitations in the no-throw-literal rule.

To avoid conflicts between rules, this rule does not report non-error values used in throw statements in async functions, even though these lead to Promise rejections. To lint for these cases, use the no-throw-literal rule.

When Not To Use It

If you’re using custom non-error values as Promise rejection reasons, you can turn off this rule.

Источник

Name already in use

archive-website / docs / 6.0.0 / rules / prefer-promise-reject-errors.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

require using Error objects as Promise rejection reasons (prefer-promise-reject-errors)

It is considered good practice to only pass instances of the built-in Error object to the reject() function for user-defined errors in Promises. Error objects automatically store a stack trace, which can be used to debug an error by determining where it came from. If a Promise is rejected with a non- Error value, it can be difficult to determine where the rejection occurred.

This rule aims to ensure that Promises are only rejected with Error objects.

This rule takes one optional object argument:

  • allowEmptyReject: true ( false by default) allows calls to Promise.reject() with no arguments.

Examples of incorrect code for this rule:

Examples of correct code for this rule:

Examples of correct code for this rule with the allowEmptyReject: true option:

Due to the limits of static analysis, this rule cannot guarantee that you will only reject Promises with Error objects. While the rule will report cases where it can guarantee that the rejection reason is clearly not an Error , it will not report cases where there is uncertainty about whether a given reason is an Error . For more information on this caveat, see the similar limitations in the no-throw-literal rule.

To avoid conflicts between rules, this rule does not report non-error values used in throw statements in async functions, even though these lead to Promise rejections. To lint for these cases, use the no-throw-literal rule.

When Not To Use It

If you’re using custom non-error values as Promise rejection reasons, you can turn off this rule.

Источник

prefer-promise-reject-errors

Требуется использовать объекты Error в качестве причин отказа Promise

Error object to the reject() function for user-defined errors in Promises. Error objects automatically store a stack trace, which can be used to debug an error by determining where it came from. If a Promise is rejected with a non- Error value, it can be difficult to determine where the rejection occurred.» onmousemove=»i18n(this)»>Считается хорошей практикой передавать только экземпляры встроенного объекта Error в функцию reject() для пользовательских ошибок в Promises. Объекты Error автоматически сохраняют трассировку стека, которую можно использовать для отладки ошибки путем определения ее источника. Если Promise отклоняется со значением, отличным от Error , может быть трудно определить, где произошло отклонение.

Rule Details

Error objects.» onmousemove=»i18n(this)»>Это правило направлено на то, чтобы обещания отклонялись только с объектами Error .

Options

Это правило принимает один необязательный аргумент объекта:

  • allowEmptyReject: true ( false by default) allows calls to Promise.reject() with no arguments.» onmousemove=»i18n(this)»> allowEmptyReject: true ( по умолчанию false ) разрешает вызовы Promise.reject() без аргументов.

Примеры неправильного кода для этого правила:

Примеры правильного кода для этого правила:

allowEmptyReject: true option:» onmousemove=»i18n(this)»>Примеры правильного кода для этого правила с параметром allowEmptyReject: true :

Known Limitations

Error objects. While the rule will report cases where it can guarantee that the rejection reason is clearly not an Error , it will not report cases where there is uncertainty about whether a given reason is an Error . For more information on this caveat, see the similar limitations in the no-throw-literal rule.’ onmousemove=»i18n(this)»>Из-за ограничений статического анализа это правило не может гарантировать, что вы отклоните только объекты Promises с Error Хотя правило будет сообщать о случаях, когда оно может гарантировать, что причина отклонения явно не является Error , оно не будет сообщать о случаях, когда существует неопределенность в отношении того, является ли данная причина Error . Для получения дополнительной информации об этом предостережении см. аналогичные ограничения в правиле no-throw-literal .

throw statements in async functions, even though these lead to Promise rejections. To lint for these cases, use the no-throw-literal rule.’ onmousemove=»i18n(this)»>Чтобы избежать конфликтов между правилами, это правило не сообщает о значениях без ошибок, используемых в операторах throw в асинхронных функциях, даже если это приводит к отклонению Promise. Чтобы проверить эти случаи, используйте правило no-throw-literal .

Когда не использовать его

Если вы используете пользовательские неошибочные значения в качестве причин отклонения обещаний,вы можете отключить это правило.

Источник

title layout

prefer-promise-reject-errors — Rules

doc

require using Error objects as Promise rejection reasons (prefer-promise-reject-errors)

It is considered good practice to only pass instances of the built-in Error object to the reject() function for user-defined errors in Promises. Error objects automatically store a stack trace, which can be used to debug an error by determining where it came from. If a Promise is rejected with a non-Error value, it can be difficult to determine where the rejection occurred.

Rule Details

This rule aims to ensure that Promises are only rejected with Error objects.

Options

This rule takes one optional object argument:

  • allowEmptyReject: true (false by default) allows calls to Promise.reject() with no arguments.

Examples of incorrect code for this rule:

/*eslint prefer-promise-reject-errors: "error"*/

Promise.reject("something bad happened");

Promise.reject(5);

Promise.reject();

new Promise(function(resolve, reject) {
  reject("something bad happened");
});

new Promise(function(resolve, reject) {
  reject();
});

Examples of correct code for this rule:

/*eslint prefer-promise-reject-errors: "error"*/

Promise.reject(new Error("something bad happened"));

Promise.reject(new TypeError("something bad happened"));

new Promise(function(resolve, reject) {
  reject(new Error("something bad happened"));
});

var foo = getUnknownValue();
Promise.reject(foo);

Examples of correct code for this rule with the allowEmptyReject: true option:

/*eslint prefer-promise-reject-errors: ["error", {"allowEmptyReject": true}]*/

Promise.reject();

new Promise(function(resolve, reject) {
  reject();
});

Known Limitations

Due to the limits of static analysis, this rule cannot guarantee that you will only reject Promises with Error objects. While the rule will report cases where it can guarantee that the rejection reason is clearly not an Error, it will not report cases where there is uncertainty about whether a given reason is an Error. For more information on this caveat, see the similar limitations in the no-throw-literal rule.

To avoid conflicts between rules, this rule does not report non-error values used in throw statements in async functions, even though these lead to Promise rejections. To lint for these cases, use the no-throw-literal rule.

When Not To Use It

If you’re using custom non-error values as Promise rejection reasons, you can turn off this rule.

Further Reading

  • no-throw-literal
  • Warning: a promise was rejected with a non-error

Version

This rule was introduced in ESLint 3.14.0.

Resources

  • Rule source
  • Documentation source

Требуется использовать объекты Error в качестве причин отказа Promise

Считается хорошей практикой передавать только экземпляры встроенного объекта Error в функцию reject() для пользовательских ошибок в Promises. Объекты Error автоматически сохраняют трассировку стека, которую можно использовать для отладки ошибки путем определения ее источника. Если Promise отклоняется со значением, отличным от Error , может быть трудно определить, где произошло отклонение.

Rule Details

Это правило направлено на то, чтобы обещания отклонялись только с объектами Error .

Options

Это правило принимает один необязательный аргумент объекта:

  • allowEmptyReject: true ( по умолчанию false ) разрешает вызовы Promise.reject() без аргументов.

Примеры неправильного кода для этого правила:

Promise.reject("something bad happened");Promise.reject(5);Promise.reject();new Promise(function(resolve, reject) {  reject("something bad happened");});new Promise(function(resolve, reject) {  reject();});

Примеры правильного кода для этого правила:

Promise.reject(new Error("something bad happened"));Promise.reject(new TypeError("something bad happened"));new Promise(function(resolve, reject) {  reject(new Error("something bad happened"));});var foo = getUnknownValue();Promise.reject(foo);

Примеры правильного кода для этого правила с параметром allowEmptyReject: true :

Promise.reject();new Promise(function(resolve, reject) {  reject();});

Known Limitations

Из-за ограничений статического анализа это правило не может гарантировать, что вы отклоните только объекты Promises с Error Хотя правило будет сообщать о случаях, когда оно может гарантировать, что причина отклонения явно не является Error , оно не будет сообщать о случаях, когда существует неопределенность в отношении того, является ли данная причина Error . Для получения дополнительной информации об этом предостережении см. аналогичные ограничения в правиле no-throw-literal .

Чтобы избежать конфликтов между правилами, это правило не сообщает о значениях без ошибок, используемых в операторах throw в асинхронных функциях, даже если это приводит к отклонению Promise. Чтобы проверить эти случаи, используйте правило no-throw-literal .

Когда не использовать его

Если вы используете пользовательские неошибочные значения в качестве причин отклонения обещаний,вы можете отключить это правило.

  • no-throw-literal

Version

Это правило было введено в ESLint v3.14.0.

Further Reading

Avatar image for bluebirdjs.com

Resources

  • Rule source
  • Tests source


ESLint

8.30

  • prefer-object-has-own

    Запретить использование Object.prototype.hasOwnProperty.call()и предпочесть Object.hasOwn()Некоторые проблемы,о которых сообщает это правило,автоматически устраняются командой

  • prefer-object-spread

    Запретить использование Object.assign с литералом в качестве первого аргумента и предпочесть вместо него использование spread.

  • prefer-regex-literals

    Запретить использование конструктора RegExp в пользу литералов регулярных выражений Некоторые проблемы,о которых сообщает это правило,устранимы вручную предложениями редактора

  • prefer-rest-params

    Требуйте параметры отдыха вместо аргументов В ES2015 есть параметры отдыха.

The code

Let’s consider a simple function that returns a Promise that can either resolve or reject depending on the value of
the first argument:

export default function promiseMe(result, timeout = 1000) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (result instanceof Error || result.startsWith("Error")) {
                reject(result)
            } else {
                resolve(result)
            }
        }, timeout)
    })
}

While testing async code with Jest the only thing to remember is to return Promise from the test so that Jest can
wait for it to resolve or to reject. The cleanest way is to do it with .resolves matcher:

const successMessage = "Done.";

// with async/await
it("resolves (1)", async () => {
    await expect(promiseMe(successMessage)).resolves.toEqual(successMessage);
});

// without async/await
it("resolves (2)", () => {
    return expect(promiseMe(successMessage)).resolves.toEqual(successMessage);
});

In case the Promise rejects and the test did not expect that, Jest reports an error:

Error: expect(received).resolves.toEqual()

Received promise rejected instead of resolved
Rejected to value: [...]

But what if one want to test Promise rejection and verify the rejection reason?

Try-catch with async/await (bad)

It looks like using try-catch with async/await is the easiest way to achieve this as the rejected value is thrown:

it("rejects (bad)", async () => {
    try {
        await promiseMe("Error");
    } catch (e) {
        expect(e).toEqual("Error");
    }
});

But wait. What happens when the Promise returned by promiseMe function won’t reject, but it resolves instead? Well, the test still passes, as the catch block is never reached.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#promise_rejection

Try-catch with async/await (better)

To overcome that issue, one could expect that the actual assertion will be executed and fail the test if it does not happen.
This can be done pretty easily with expect.assertions which verifies that a certain number of assertions are called
during a test:

it("rejects (better)", async () => {
    expect.assertions(1);
    try {
        await promiseMe("Error");
    } catch (e) {
        expect(e).toEqual("Error");
    }
});

Now, when there is no rejection, the test fails:

Error: expect.assertions(1)

Expected one assertion to be called but received zero assertion calls.

.rejects (best)

To make the code even more expressive .rejects matcher can be used:

it("rejects (best)", async () => {
    await expect(promiseMe("Error")).rejects.toEqual("Error");
});

When there is no rejection, Jest reports an error:

Error: expect(received).rejects.toEqual()  
  
Received promise resolved instead of rejected  
Resolved to value: [...]

If the rejected value is an Error object, toThrow matcher can be used:

it("rejects (best)", async () => {
    await expect(promiseMe(new Error(errorMessage))).rejects.toThrow(errorMessage);
    await expect(promiseMe(new Error(errorMessage))).rejects.toThrow(Error); // type check
    await expect(promiseMe(new Error(errorMessage))).rejects.toThrow(new Error(errorMessage));
});

Понравилась статья? Поделить с друзьями:
  • Expected string or bytes like object python ошибка
  • Expected package found eof как исправить go
  • Expected linebreaks to be lf but found crlf как исправить
  • Expected function or variable vba ошибка
  • Expected error junit