[译]window.onerror事件
本文翻译youtube上的up主kudvenkat的javascript tutorial播放单
源地址在此:
https://www.youtube.com/watch?v=PMsVM7rjupU&list=PL6n9fhu94yhUA99nOsJkKXBqokT3MBK0b
总的来说,在Javascript中我们用try/catch语句来获取错误.如果一个错误不是由try..catch语句块捕捉的话,那么则会发出一个onerror事件.
当一个错误如下例中一样出现后,我们想要将一个函数赋给window.onerror事件.这个函数作为onerror事件的时间处理者,有3个参数:
message表示错误信息
URL表示错误出现的位置
line表示错误出现在第几行
Javascript window onerror事件例子:
window.onerror = function (message, url, line) { alert("Message : " + message + "\nURL : " + url + "\nLine Number : " + line); // Return true to supress the browser error messages (like in older versions of Internet Explorer) return true; } NonExistingFunction();
如果错误被try..catch语句捕捉到的话,那么onerror事件就不会产生,当场面上有没有被处理的exception的时候onerror事件才会发生.
window.onerror = function (message, url, line) { alert("Message : " + message + "\nURL : " + url + "\nLine Number : " + line); // Return true to supress the browser error messages (like in older versions of Internet Explorer) return true; } try { NonExistingFunction(); } catch (e) { document.write(e.message); }
Output : 'NonExistingFunction' is undefined
onerror事件处理方法同样可以用于HTML元素:在以下的例子中,因为image不存在,我们会得到"There is a problem loading the image"错误
<script type="text/javascript"> function imageErrorHandler() { alert("There is a problem loading the image"); } </script> <img src="NonExistingImage.jpg" onerror="imageErrorHandler()" />
小白前端学习之路
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步