本文翻译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()" />