Javascript 无法使用 fetch 捕获错误

标签 javascript node.js express promise fetch

我有一个 authService,它具有以下提取

export const handleForm = () => {

    return fetch('http://localhost:5000/login')
        .then(response => {
            if (!response.ok) {
                throw new Error("Email or password incorrect");
            } else {
                return response.json();
            }
        })
        .then(json => json)
        .catch(error => error);
};

我正在从我的 Controller 调用该方法:

form.onsubmit = function (e) {
    handleForm(e)
        .then(response => {
            console.log(response);
            //setAuthenticatedUser(response);
            // setDomUser(response.user);
        })
        .catch(error => {
            console.log(error);
            document.querySelector('#error').innerHTML = error;
        })
};

我尝试了一些方法来在 Controller 中捕获错误 但我不断收到响应回调。 我的 authService 错误未被捕获

我已经尝试过

  • 抛出新的Error();
  • Promise.reject();

最佳答案

参见Promise.prototype.catch() :

Syntax Section

p.catch(onRejected);

[...]

The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.

使用.catch(error => error)作为回调返回异常。所以它既不会“抛出错误”,也不会“返回一个本身被拒绝的 Promise”。它返回的 promise 因此被解决,而不是被拒绝。

只需删除 .catch(error => error) 即可。当你这样做时,还要删除 .then(json => json) 因为它没有用。

关于Javascript 无法使用 fetch 捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53896991/

相关文章:

javascript - 以编程方式设置剑道网格的下一行

javascript - 当我使用 ng-model 和 ng-change 时如何设置默认值来选择?

javascript - 使用 Knex.js 创建嵌套返回模型

javascript - 如何使用 Multer 验证 Express 中文件上传的大小?

javascript - 如何在express js中将数组值发送到html页面

javascript - 如何防止签名 token 用户通过浏览器开发者工具访问 API 响应?

javascript - 如何在 Firefox 或 Chrome 中模拟文本框的按键?

javascript - app.get() 被多次调用 Express

javascript - Node js multer 文件上传不起作用。 req.file 和 req.files 始终未定义

node.js - Node JS 流 : Understanding data concatenation