【问题标题】:catching Uncaught (in promise) DOMException javascript捕获 Uncaught (in promise) DOMException javascript
【发布时间】:2018-01-27 12:17:23
【问题描述】:

当用户上传损坏的文件或不是图像的文件时,我试图显示错误。当您上传不是图像的文件时,会出现 Uncaught (in promise) DOMException: 。

如何捕获此错误并将其显示在 div 中。我试过 try and catch,window.onerror 但在发生此错误时不执行任何操作。

这是我的代码。

$('.upload-result').on('click', function(ev){
      if($('#upload').get(0).files.length === 0){
        $('.nofile').show();
      }else{
        if($.inArray($('#upload').val().split('.').pop().toLowerCase(), ['gif','png','jpg','jpeg']) == -1){
            $('.invalid-file').show();
        }else{

          $uploadCrop.croppie('result',{ //error occurs here 
            type: 'canvas',
            size: 'viewport'
          }).then(function (resp){
            $.ajax({
              url: "{{url('dashboard/program/imageUpload')}}",
              type: "POST",
              data: {"image":resp, "id":id},
              success:function(data){
                $('.success').show(0, function(){
                  setTimeout(function(){
                    location.href = "{{route('program')}}"
                  }, 1000);
                });
              },
              error: function (xhr, textStatus, errorThrown) {
                  alert("fail");
              }
            });
          });
        }
      }

    });

    window.onerror = function() {
      alert("an error");
    }

【问题讨论】:

  • 您是否尝试将.catch(function(err) {... 添加到您的$uploadCrop.croppie 通话中?
  • 我做了,但我不确定我是否做得正确,因为我找不到 catch 方法。
  • 错误是什么? resp 是什么? id 定义在哪里?

标签: javascript jquery validation error-handling


【解决方案1】:

在 then 之后添加一个 catch 语句,可以保证您的应用程序安全,并且您可以简单地动态处理各种错误。

$uploadCrop.croppie('result', {
   //error occurs here
   type: 'canvas',
   size: 'viewport',
})
.then(function(resp) {
   $.ajax({
      url: "{{url('dashboard/program/imageUpload')}}",
      type: 'POST',
      data: { image: resp, id: id },
      success: function(data) {
         $('.success').show(0, function() {
            setTimeout(function() {
               location.href = "{{route('program')}}"
            }, 1000)
         })
      },
      error: function(xhr, textStatus, errorThrown) {
         alert('fail')
      },
   })
})
.catch(err => /* handle your error here */)

重要的部分是这样的:

.catch(err => /* handle your error here */)

如果您想了解更多关于 Promise 及其存在的原因以及如何使用它们的信息,请阅读以下内容:MDN Promises medium.com: promises explained with gambling

【讨论】:

    猜你喜欢
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2021-04-28
    • 2021-04-15
    • 2016-10-24
    • 2019-06-09
    相关资源
    最近更新 更多