JavaScript DHTML/Development/Error Exceptions

Материал из Web эксперт
Перейти к: навигация, поиск

A Custom Object Exception

/*
JavaScript Bible, Fourth Edition
by Danny Goodman 
John Wiley & Sons CopyRight 2001
*/

<HTML>
<HEAD>
<TITLE>Throwing a Custom Error Object Exception</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var letters = new Array("A","B","C","D","E")
function getErrorObj(msg) {
    var err = new Error(msg)
    // take care of IE5/5.5
    if (!err.message) {
        err.message = msg
    }
    err.name = "MY_ERROR"
    return err
}
function getLetter(fld) {
    try {
    var inp = parseInt(fld.value, 10)
        if (isNaN(inp)) {
            throw getErrorObj("Entry was not a number.")
        }
        if (inp < 1 || inp > 5) {
            throw getErrorObj("Enter only 1 through 5.")
        }
        fld.form.output.value = letters[inp]
    }
    catch (e)  {
        switch (e.name) {
            case "MY_ERROR" :
                alert(e.message)
                fld.form.output.value = ""
                fld.focus()
                fld.select()
                break
            default :
                alert("Reload the page and try again.")
        }
    }
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Throwing a Custom Error Object Exception</H1>
<HR>
<FORM>
Enter a number from 1 to 5: 
<INPUT TYPE="text" NAME="input" SIZE=5>
<INPUT TYPE="button" VALUE="Get Letter" onClick=getLetter(this.form.input)>
Matching Letter is:<INPUT TYPE="text" NAME="output" SIZE=5>
</FORM>
</BODY>
</HTML>



An Exception Handling Example

<HTML>
<HEAD><TITLE>Exception Test</TITLE></HEAD>
<SCRIPT LANGUAGE="JavaScript"><!--
function primeTest(n) {
 document.write("Testing "+n+": ")
 try {
  if(n < 1 || n > 20) 
      throw "It"s out of range"
  for(var i = 2; i < n; ++i){
     if(n % i == 0) 
        throw "It"s divisible by " + i
  }
  document.writeln("It"s prime.<BR>")
 }
 catch (exception) {
  document.writeln(exception+".<BR>")
 }
}
--></SCRIPT>
<BODY>
<P>This script only works with Internet Explorer 5, Navigator 6, or later browsers.</P>
<SCRIPT LANGUAGE="JavaScript"><!--
for(i = 0; i <= 21; ++i) {
 primeTest(i)
}
--></SCRIPT>
</BODY>
</HTML>



Catching an Error

<HTML>
<TITLE>Catch that error!</TITLE>
<SCRIPT> 
function catchError(errString) { 
   try { 
      try { 
         if (errString == 42) 
            throw new Error (42, "errString is 42 !"); 
         else 
            throw new Error (0, "errString is NOT 42 !"); 
      } 
      catch(e) { 
         if (e.number == 42) 
            return (e.description + " Got this one!"); 
         else 
            throw e; // re-throw the error 
      } 
    } 
    catch (e){ 
       return(e.description + " This one not handled here!"); 
    } 
} 
</SCRIPT>
</HEAD>
<BODY>
<H1> 
Catch that error! 
</H1>
<FORM name="theForm">
<TABLE>
<TR><TD colspan=2> We can handle 42: </TD><TD><INPUT type=text name=errText size=40 value="42"></TD></TR>
<TR><TD colspan=2></TD>
<TD><INPUT type=button name=btnThrow value="Catch it!" onClick="alert(catchError(document.theForm.errText.value));">
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>



Catching the "Object Expected" Error

<HTML>
<BODY>
<H1>
<SCRIPT> 
function dosomething() { 
} 
function goodFunc(){ 
   try { 
      doSomething(); 
   } 
   catch (e) { 
      if (e.description == "Object expected") { 
         alert("Cannot find a function named doSomething!"); 
      } 
      else { 
         alert ("Other error" + e.description); 
      } 
   } 
} 
</SCRIPT>
</H1>
<FORM>
<INPUT type=button value="Click" onClick="goodFunc();">
</FORM>
</BODY>
</HTML>



Controlling Script Errors

/*
JavaScript Bible, Fourth Edition
by Danny Goodman 
John Wiley & Sons CopyRight 2001
*/

<HTML>
<TITLE>Error Dialog Control</TITLE>
<SCRIPT LANGUAGE="JavaScript1.1">
// function with invalid variable value
function goWrong() {
    var x = fred
}
// turn off error dialogs
function errOff() {
    window.onerror = doNothing
}
// turn on error dialogs with hard reload
function errOn() {
    window.onerror = handleError
}
// assign default error handler
window.onerror = handleError
// error handler when errors are turned off...prevents error dialog
function doNothing() {return true}
function handleError(msg, URL, lineNum) {
    var errWind = window.open("","errors","HEIGHT=270,WIDTH=400")
    var wintxt = "<HTML><BODY BGCOLOR=RED>"
    wintxt += "<B>An error has occurred on this page.  "
    wintxt += "Please report it to Tech Support.</B>"
    wintxt += "<FORM METHOD=POST ENCTYPE="text/plain" "
    wintxt += "ACTION=mailTo:support4@dannyg.ru >"
    wintxt += "<TEXTAREA NAME="errMsg" COLS=45 ROWS=8 WRAP=VIRTUAL>"
    wintxt += "Error: " + msg + "\n"
    wintxt += "URL: " + URL + "\n"
    wintxt += "Line: " + lineNum + "\n"
    wintxt += "Client: " + navigator.userAgent + "\n"
    wintxt += "-----------------------------------------\n"
    wintxt += "Please describe what you were doing when the error occurred:"
    wintxt += "</TEXTAREA><P>"
    wintxt += "<INPUT TYPE=SUBMIT VALUE="Send Error Report">"
    wintxt += "<INPUT TYPE=button VALUE="Close" onClick="self.close()">"
    wintxt += "</FORM></BODY></HTML>"
    errWind.document.write(wintxt)
    errWind.document.close()
    return true
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform">
<INPUT TYPE="button" VALUE="Cause an Error" onClick="goWrong()"><P>
<INPUT TYPE="button" VALUE="Turn Off Error Dialogs" onClick="errOff()">
<INPUT TYPE="button" VALUE="Turn On Error Dialogs" onClick="errOn()">
</FORM>
</BODY>
</HTML>



Nested Exception Handling (This script only works with Internet Explorer 5, Navigator 6, or later browsers)

<HTML>
<HEAD><TITLE>Exception Test</TITLE></HEAD>
<SCRIPT LANGUAGE="JavaScript"><!--
function selected(n) {
 try {
  try {
   if (n % 3 == 1) throw "Try again"
  }
  catch (ex1) {
   if(ex1 == "Try again")
   return false
  }
  if (n % 7 != 0) throw "No way"
 }
 catch (ex2) {
  if(ex2 != "Try again") return false
 }
 return true
}
--></SCRIPT>
<BODY>
<SCRIPT LANGUAGE="JavaScript"><!--
for(i = 1; i <= 100; ++i) {
 if (selected(i)) document.writeln(i+"<BR>")
}
--></SCRIPT>
</BODY>
</HTML>



Throwing an Error

<HTML>
<HEAD>
<TITLE>Throw that error!</TITLE>
<SCRIPT> 
function throwError(errString) { 
   try { 
      throw new Error (42, errString); 
   } 
   catch(e){ 
      alert("Error number: " + e.number + "; Description: " + e.description) 
   } 
} 
</SCRIPT>
</HEAD>
<BODY>
<H1> 
Throw that error! 
</H1>
<FORM name="theForm">
<TABLE>
<TR>
<TD colspan=2> Enter text for the error: </TD>
<TD>
<INPUT type=text name=errText size=40>
</TD>
</TR>
<TR>
<TD colspan=2>
</TD>
<TD>
<INPUT type=button name=btnThrow value="Throw it!" onClick="throwError(document.theForm.errText.value);">
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>



Throwing an Error Object Exception

/*
JavaScript Bible, Fourth Edition
by Danny Goodman 
John Wiley & Sons CopyRight 2001
*/

<HTML>
<HEAD>
<TITLE>Throwing an Error Object Exception</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var letters = new Array("A","B","C","D","E")
function getErrorObj(msg) {
    var err = new Error(msg)
    // take care of IE5/5.5
    if (!err.message) {
        err.message = msg
    }
    return err
}
function getLetter(fld) {
    try {
        var inp = parseInt(fld.value, 10)
        if (isNaN(inp)) {
            throw getErrorObj("Entry was not a number.")
        }
        if (inp < 1 || inp > 5) {
            throw getErrorObj("Enter only 1 through 5.")
        }
        fld.form.output.value = letters[inp]
    }
    catch (e)  {
        alert(e.message)
        fld.form.output.value = ""
        fld.focus()
        fld.select()
    }
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Throwing an Error Object Exception</H1>
<HR>
<FORM>
Enter a number from 1 to 5: 
<INPUT TYPE="text" NAME="input" SIZE=5>
<INPUT TYPE="button" VALUE="Get Letter" onClick=getLetter(this.form.input)>
Matching Letter is:<INPUT TYPE="text" NAME="output" SIZE=5>
</FORM>
</BODY>
</HTML>



Throwing String Exceptions

<HTML>
<HEAD>
<TITLE>Throwing a String Exception</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var letters = new Array("A","B","C","D","E")
function getLetter(fld) {
    try {
        var inp = parseInt(fld.value, 10)
        if (isNaN(inp)) {
            throw "Entry was not a number."
        }
        if (inp < 1 || inp > 5) {
            throw "Enter only 1 through 5."
        }
        fld.form.output.value = letters[inp-1]
    }
    catch (e)  {
        alert(e)
        fld.form.output.value = ""
        fld.focus()
        fld.select()
    }
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Throwing a String Exception</H1>
<HR>
<FORM>
Enter a number from 1 to 5: 
<INPUT TYPE="text" NAME="input" SIZE=5>
<INPUT TYPE="button" VALUE="Get Letter" onClick=getLetter(this.form.input)>
Matching Letter is:<INPUT TYPE="text" NAME="output" SIZE=5>
</FORM>
</BODY>
</HTML>



Using the onError Event Handler

<HTML>
<HEAD>
<TITLE>Handling Errors with onError</TITLE>
<SCRIPT><!--
function errorHandler(errorMessage,url,line) {
 document.write("<P><B>Error message:</B> "+errorMessage+"<BR>")
 document.write("<B>URL:</B> "+url+"<BR>")
 document.write("<B>Line number:</B> "+line+"</P>")
 return true
}
   
onerror = errorHandler
// --></SCRIPT>
</HEAD>
<BODY>
<H1>Handling Errors with onError</H1>
<FORM>
<INPUT TYPE="BUTTON" ONCLICK="createAnError()"
VALUE="Click here to generate an error.">
</FORM>
</BODY>
</HTML>