【问题标题】:Axios: Not going into catch method with errorAxios:没有进入错误的catch方法
【发布时间】:2019-03-03 11:19:21
【问题描述】:

我有一个编辑合同名称的功能。我使用特定 ID 向后端 API 调用 axios 请求。对于每种情况,我都会调用一条甜蜜的消息。

axios({
       url: '/api/contract/' + id,
       method: 'put',
       data: {
             name: name
       }
       }) .then((response) => {
          this.$emit('fetchAll');
          swal({
               title: "Success!",
               icon: "success"
          });
       }) .catch(error => {
          this.errors = error.response.data.errors;
          swal({
             title: "Error",
             text: error.response.data.message,
             icon: "error"
       });
});

有回应:

403: You are not authorized to edit this contract.

Laravel 控制器中的错误处理:

if (Bouncer::cannot('contract-destroy'))
    abort('403', "You are not authorized to delete this contract");

即使请求出错,也会弹出成功消息。

【问题讨论】:

  • 你是如何从 Larave 返回错误的?
  • 查看浏览器的 Network 控制台。那里的响应状态如何?
  • 你能显示控制台的屏幕截图吗?
  • @Devon 如果在 promise 的解析回调中抛出错误,它会抛出异常并触发拒绝(捕获)回调。

标签: javascript laravel vue.js axios


【解决方案1】:

对于您的爱人,将密钥 icon 更改为 type。否则我认为默认情况下会显示成功消息。所以代码应该是

axios({
       url: '/api/contract/' + id,
       method: 'put',
       data: {
             name: name
       }
       }) .then((response) => {
          this.$emit('fetchAll');
          swal({
               title: "Success!",
               type: "success"
          });
       }) .catch(error => {
          this.errors = error.response.data.errors;
          swal({
             title: "Error",
             text: error.response.data.message,
             type: "error"
       });
});

【讨论】:

  • 这样我得到了没有图标的成功消息
  • 啊,你用的是什么版本的 sweetalert2?我在文档中的任何地方都看不到 icon 选项 - sweetalert2.github.io
  • 我在我的项目中使用 sweetalert 2.1.0。但是警报应该不是问题,它是来自 axios 的错误回调。
【解决方案2】:

我现在发现了问题,回调参数应该定义为Object。我不知道为什么会出现问题,但现在已修复。

axios({
   url: '/api/contract/' + id,
   method: 'put',
   data: {
         name: name
   }
   }) .then(({data}) => { <-------instead of (response)
      this.$emit('fetchAll');
      swal({
           title: "Success!",
           icon: "success"
      });
   }) .catch(error => {
      this.errors = error.response.data.errors;
      swal({
         title: "Error",
         text: error.response.data.message,
         icon: "error"
   });

});

【讨论】:

  • 这确实不是解决方案。这与您的原始代码在功能上的差异为零
  • @Phil 这对我来说似乎很奇怪,但这是唯一有效的更改
  • 我怀疑您可能只是修复了一些不匹配的大括号或类似的东西(并且您问题中的代码不是精确的副本)。如果您使用更好的缩进,您可能会看到更好
  • 代码是一个副本,我真的只是改变了参数周围的大括号。一旦我删除它们,它就会停止工作。
  • 对不起,我真的不买它。 (response) =&gt; { ... }({data}) =&gt; { ... } 甚至 () =&gt; { ... } 没有什么不同,因为您不使用 responsedata
猜你喜欢
  • 2019-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-20
  • 2018-04-19
  • 2020-09-10
  • 2019-08-05
  • 2021-06-28
相关资源
最近更新 更多