php 中是可以自定義程式的錯誤和異常處理函數的(handler).于是,我在想,javascript 中是否也存在和PHP中一樣的異常和錯誤處理函數呢?
try{}catch(){} 這種捕捉異常和錯誤的機制,我們很熟悉,當然這在javascript 中也是支援的。那麼,javascript 中有類似php中的魔術方法嗎?來定義
異常和錯誤的handler()????
于是,google之,找到了下面的這篇文章,确實可以:)!!!!!!
參考: http://www.javascripter.net/faq/err_demo.htm?customHandler
Error Handling Demo javascript 自定義錯誤處理 Contents | JavaScript FAQ | Error Handling | Question: Can I dynamically change the JavaScript error handler? Answer: Yes. To change the JavaScript error handler, just set window.onerror to the name of the function that will serve as your new error handler. Here's a demo that lets you test three different error handlers: - the browser's default error handler
- an error handler that displays a customized alert box
- a "silent" error handler that suppresses all error messages. Custom Error Handler Silent Error Handler Default Error Handler
- Use the select box to set or change the error handler.
- Click Fire an Error to test the active error handler.
Below is the source code of the error handling functions used in this demo: function defaultHandler() {return false}
function silentHandler() {return true}
function customHandler(desc,page,line,chr) {
alert(
'JavaScript error occurred! \n'
+'The error was handled by '
+'a customized error handler.\n'
+'\nError description: \t'+desc
+'\nPage address: \t'+page
+'\nLine number: \t'+line
)
return true
} |