[英]catching Uncaught (in promise) DOMException javascript
I'm trying to display the error when a user upload a corrupt file or file that is not and image. 当用户上载损坏的文件或文件不是image时,我试图显示错误。 When you upload a file that is not an image an Uncaught (in promise) DOMException: appear. 当您上载不是图像的文件时,将出现“未捕获(承诺)”的DOMException :。
How do I catch this error and display it in a div. 如何捕获此错误并将其显示在div中。 I've tried try and catch, window.onerror but doesn't do anything when this error occur. 我试过尝试并捕获window.onerror,但是在发生此错误时不执行任何操作。
This is my code. 这是我的代码。
$('.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");
}
Adding a catch statement after the then, keeps your application safe and you can simply handle various errors dynamically. 然后添加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 */)
The important part is this: 重要的部分是:
.catch(err => /* handle your error here */)
If you want to learn more about Promises and why they are there and how to use them, then just read this: MDN Promises or medium.com: promises explained with gambling 如果您想了解有关Promises的更多信息,为何存在于其中以及如何使用它们,请阅读以下内容: MDN Promises 或 medium.com:用赌博解释的诺言
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.