js錯誤處理的方式多種,比較常用的是 try-catch-finally。
現在用onerror(該方法觸發時有3個三個參數:ErrorMessage(錯誤報告消息)、URL(發生錯誤的URL地址)、LineNumber(錯誤所在行數))處理.
我們在開發階段希望將錯誤信息提出出來,則可以這樣子處理:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type="text/javascript"> window.onerror = function(sMessage, sUrl, sLine) { alert("錯誤信息:" + sMessage + "\n錯誤URL: " + sUrl + "\n錯誤Line Number: " + sLine); return true;//返回true則瀏覽器將不會在狀態欄中提示錯誤;默認返回false,會在狀態欄提示錯誤信息。 } </script> </head> <body> <input type="button" value="提交" onclick="aa()"/> </body> </html>
?上面的代碼中,調用了一個不存在的aa函數,則瀏覽器會顯示如下錯誤:
還有一種情況是頁面代碼本身沒有問題,用戶的過快操作,頁面 JS 代碼還沒有執行完成就直接轉到其他頁面也會出現這樣的錯誤。這種錯誤拋給用戶是相當不友好的,我們可以用下面的代碼屏蔽掉所有的錯誤:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type="text/javascript"> function doNothing() { return true; } window.onerror = doNothing; </script> </head> <body> <input type="button" value="提交" onclick="aa()"/> </body> </html>?
這個時候調用不存在的函數aa時,頁面不會報任何錯誤。
這個方法在開發階段建議注釋掉,發布的時候加上去。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
