Web development code: JavaScript error handling: try ... catch statement, try with a confirmation box ... catch Statement

1, try ... catch Statement

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>now test</title> 
<script>
	var txt="";
	function myFunction(){
	try{
		adddlert("welcome to hk!");
	}
	catch(err){
		txt="本页有一个错误。\n\n";
		txt+="错误描述:" + err.message + "\n\n";
		txt+="点击确定继续。\n\n";
		alert(txt);
	}	
	}
	</script>
</head>
<body>
<input type="button" value="查看消息" onclick="myFunction()"/>
</body>
</html> 

2, try to confirm with box ... catch Statement

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>now test</title> 
<script>
	var txt="";
	function myFunction(){
	try{
		adddlert("welcome to hk!");
	}
	catch(err){
		txt="本页有一个错误。\n\n";
		txt+="错误描述:" + err.message + "\n\n";
		txt+="点击确定继续。\n\n";
		if(confirm(txt)){
			document.location.hrf="//www.baidu.com/";
		}
	}	
	}
	</script>
</head>
<body>
<input type="button" value="查看消息" onclick="myFunction()"/>
</body>
</html> 

3, onerror event

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>now test</title> 
<script>
	onerror=myFunction;
	var txt="";
	function myFunction(msg,url,l){
		txt="本页有一个错误。\n\n";
		txt+="错误:" + msg + "\n";
		txt+="URL:" + url + "\n";
		txt+="行:" + l + "\n\n";
		txt+="点击确定继续。\n\n";
		alert(txt);
		return true;
	}
	function message(){
		adddlert("welcome to hk!");
	}
	</script>
</head>
<body>
<input type="button" value="查看消息" onclick="message()"/>
</body>
</html> 

Guess you like

Origin blog.csdn.net/weixin_43731793/article/details/94137108
Recommended