如何在 JavaScript 中捕获 ERR_FILE_NOT_FOUND 错误 [英] How to catch ERR_FILE_NOT_FOUND errors in JavaScript

查看:102
本文介绍了如何在 JavaScript 中捕获 ERR_FILE_NOT_FOUND 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 javascript 测试某个文件是否存在.(不想使用 Ajax).想使用 catch 尝试处理 ERR_FILE_NOT_FOUND 错误.我试过

I was trying to test whether certain file exist using javascript.(don't want to use Ajax). Want to use catch try to handle ERR_FILE_NOT_FOUND error. I tried

   try{
            img.attr('src', url)
        }catch(err){
            console.log("file"+ url + " doesn't exist");
        }

但它没有赶上错误.我如何赶上 ERR_FILE_NOT_FOUND 错误?

but it doesn't catch up the error.How do I catch ERR_FILE_NOT_FOUND error?

推荐答案

Chrome 这样做是为了通知.即使您使用 try-catch 正确处理错误并使用 void( ) 正确处理了 onerror这是为了防止错误 - 你无法修复它.它不受 Javascript 控制.

Chrome does it to inform. Even if you handle onerror correctly with correct error handling with try-catch and every trick with void or ( ) that is told to prevent error - you can not fix it. It is out of Javascript control.

您能做的最好的事情就是让这些错误滚动到顶部,以免使您的输出混乱.如果您还想删除每个 console.log 上混乱的行号,以获取包含相关信息的干净输出,则此方法有效.使用 \n 作为换行符.一条虚线将错误与您的输出分开.

The best you can do is to let those errors scroll away to the top, to not clutter your output. This works if you also want to remove the clutter of line numbers on each console.log to get a clean output with relevant information. Use \n as line break. A dashed line separate the errors from your output.

var logs = ""

function log(x) {
  logs += '\n\n' + x
}

//your code
try{
  img.attr('src', url)
}catch(err){
  log("file"+ url + " doesn't exist")
}

setTimeout(function(){
  console.log("%c" + logs, "border-top: dashed 2px black;")
}, 1000)

也许最好用程序末尾调用的函数替换 setTimeout.

Maybe better replace the setTimeout with a function called in end of your program.

这篇关于如何在 JavaScript 中捕获 ERR_FILE_NOT_FOUND 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆