当用户上传损坏的文件或文件时,我正在尝试显示错误。当您上传不是图像的文件时,会出现Uncaught(in promise)DOMException :.
如何捕获此错误并将其显示在div中。我尝试过try和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");
}
答案 0 :(得分:0)
在那之后添加一个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 */)
如果您想了解有关Promises的更多信息以及它们存在的原因以及如何使用它们,请阅读以下内容:MDN Promises 或 medium.com: promises explained with gambling