Я использую перехватчик ответов Axios, и после отмены запроса мне нужно разорвать цепочку обещаний. Я не хочу добавлять проверку ошибок отмененного запроса для всех запросов в моем приложении. Я пробовал Bluebird, но, похоже, это просто отмена обещаний, а не разрыв цепей. Я должен обработать ошибки в первом улове. Эта диаграмма показывает проблему в целом. Последние тогда и улов находятся в разных файлах.

Promise
.then((response) => {

)
.catch((error) => {
  // break promise here
})
.then((response) => {
 // skip
 // I don't want any extra checks here!
)
.catch((error) => {
  // skip
  // I don't want any extra checks here!
})
1
Nikronis 28 Окт 2019 в 19:18

2 ответа

Лучший ответ

Другой вариант - выдать пользовательскую ошибку, которая может быть поймана в единственном блоке catch в самом конце, вот так:

const errorHandler = require('path/to/handler')
class ProcessingError1 extends Error {
    constructor(message) {
        super(message);
        this.name = "ProcessingError1";
    }
}
class ProcessingError2 extends Error {
    constructor(message) {
        this.message = message;
        this.name = "ProcessingError2";
    }
}
const process1 = async () => {
    throw new ProcessingError1("Somethign went wrong");
};
const process2 = async () => {
    return { some: "process" };
};
const someApiCall = async () => ({ some: "response" });

someApiCall()
    .then(process1)
    .then(process2) // process2 is not run if process1 throws an error
    .catch(errorHandler);
// ErrorHandler.js

module.exports = e => {
        if (e instanceof ProcessingError1) {
            // handle error thrown from process1
        }
        else if (e instanceof ProcessingError2) {
            // handle error thrown from process2
        }
        else {
            // handle other errors as needed..
        }
    }
1
Cranky Coder 30 Окт 2019 в 12:30

Просто оставьте только один блок catch в конце, чтобы собрать все ошибки, вызванные вашей цепочкой обещаний.

Если одно обещание бросает следующее, цепочки не выполняются

Promise
.then((response) => {

)
.then((response) => {
 // skip
 // I don't want any extra checks here!
)
.catch((error) => {
  // skip
  // I don't want any extra checks here!
})
0
Karim 28 Окт 2019 в 16:20