ASP.NET Tutorial/Development/Exception — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 18:30, 26 мая 2010
Содержание
- 1 Application-level error handling
- 2 Catch exception and display exception message, Source and StackTrace (C#)
- 3 Divide By Zero With Exception
- 4 Generic error handler page
- 5 Page-level error handling
- 6 Transfer to different page based on exception type
- 7 Try to catch error when converting text value to number
- 8 Simple Calculator
Application-level error handling
<source lang="csharp">
Protected Sub Application_Error(sender as Object, ByVal e As System.EventArgs)
Dim bigError As System.Exception = Server.GetLastError() If (TypeOf AnError.GetBaseException() Is HttpRequestValidationException) Then System.Diagnostics.Trace.WriteLine(bigError.ToString) Server.ClearError() End If
End Sub</source>
Catch exception and display exception message, Source and StackTrace (C#)
<source lang="csharp">
File: Default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="ErrorHandlingTest" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="A:"></asp:Label> <asp:TextBox ID="txtA" runat="server">5</asp:TextBox><asp:Label ID="lblResult" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="B:"></asp:Label> <asp:TextBox ID="txtB" runat="server">0</asp:TextBox>
<asp:Button ID="cmdCompute" runat="server" OnClick="cmdCompute_Click" Text="Divide A / B" />
</form>
</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Drawing; public partial class ErrorHandlingTest : System.Web.UI.Page {
protected void cmdCompute_Click(object sender, EventArgs e) { try { decimal a, b, result; a = Decimal.Parse(txtA.Text); b = Decimal.Parse(txtB.Text); result = a / b; lblResult.Text = result.ToString(); lblResult.ForeColor = Color.Black; } catch (Exception err) { lblResult.Text = "Message: " + err.Message; lblResult.Text += "
"; lblResult.Text += "Source: " + err.Source; lblResult.Text += "
"; lblResult.Text += "Stack Trace: " + err.StackTrace; lblResult.ForeColor = Color.Red; } }
}</source>
Divide By Zero With Exception
<source lang="csharp">
<script language="C#" runat="server"> protected void Page_Load(object o, EventArgs e) {
try { int x; int y; x = 5; y = 0; int result = x / y; string message = "result is: " + result; Response.Write(message); } catch(DivideByZeroException) { Response.Write("divisor can"t be zero"); }
} </script></source>
Generic error handler page
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="Samples_GenericError" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Unrecoverable Error</title>
</head> <body>
<form id="form1" runat="server">
An unrecoverable error occurred and we"re still investigating the reasons. |
</form>
</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; public partial class Samples_GenericError : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { string errCode = "No error information available."; object o = Request.QueryString["ErrID"]; if (o != null) errCode = (string) o; ErrorCode.InnerHtml = errCode; string referrer = "Error path not available."; string temp = Request.UrlReferrer.ToString(); if (!String.IsNullOrEmpty(temp)) referrer = temp; Referrer.InnerHtml = referrer; }
}</source>
Page-level error handling
<source lang="csharp">
Protected Overrides Sub OnError(ByVal e As System.EventArgs)
Dim AnError As System.Exception = Server.GetLastError() If (TypeOf AnError.GetBaseException() Is SomeSpecificException) Then Response.Write("Something bad happened!") Response.StatusCode = 200 Server.ClearError() Response.End() End If
End Sub</source>
Transfer to different page based on exception type
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="Default"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Exceptions at work</title>
</head> <body>
To test this page effectively, first disable the customErrors section in the web.config file and then try again with the section enabled.
<form id="form1" runat="server">
- <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">Click to throw a NotImplementedException exception</asp:LinkButton>
- <asp:LinkButton ID="LinkButton2" runat="server" OnClick="LinkButton2_Click">Click to generate an internal error</asp:LinkButton>
- <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="missing.aspx">Click to raise a HTTP 404 error</asp:HyperLink>
</form>
</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls;
public partial class Default : System.Web.UI.Page {
protected void Page_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); if (ex is NotImplementedException) Server.Transfer("/notimplementedexception.aspx"); else Server.Transfer("/apperror.aspx"); Server.ClearError(); } protected void Page_Load(object sender, EventArgs e) { } protected void LinkButton1_Click(object sender, EventArgs e) { throw new NotImplementedException("The feature you requested is not implemented yet."); } protected void LinkButton2_Click(object sender, EventArgs e) { string test = null; Response.Write(test.ToString()); }
}</source>
Try to catch error when converting text value to number
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="TryCatch" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Try...Catch Example</title>
</head> <body>
<form id="form1" runat="server">
Simple Calculator
<asp:TextBox ID="txtValue" runat="server" />
<asp:Button Text="Do Math" runat="server" ID="btnDivide" OnClick="btnDivide_Click" />
<asp:Label ID="labMessage" runat="server" />
</form>
</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class TryCatch : System.Web.UI.Page {
protected void btnDivide_Click(object sender, EventArgs e) { try { double dVal = Convert.ToDouble(txtValue.Text); double result = dVal * 100.0; labMessage.Text = txtValue.Text + "* 100.0"; labMessage.Text += "=" + result; } catch (FormatException ex1) { labMessage.Text = "Please enter a valid number"; } catch (Exception ex2) { labMessage.Text = "Unable to compute a value with these values"; } }
}</source>
Use Global.asax to log application level exception
<source lang="csharp">
<%@ Application Language="C#" %> <%@ Import Namespace="System.Diagnostics" %> <%@ Import Namespace="System.Text" %> <script runat="server">
void Application_Start(object sender, EventArgs e) { // Code that runs on application startup } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { // Obtain the URL of the request string url = Request.Path; // Obtain the Exception object describing the error Exception error = Server.GetLastError(); // Build the message --> [Error occurred. XXX at url] StringBuilder text = new StringBuilder("Error occurred. "); text.Append(error.Message); text.Append(" at "); text.Append(url); // Write to the Event Log EventLog log = new EventLog(); log.Source = "Core35 Log"; // log.WriteEntry(text.ToString(), EventLogEntryType.Error); }
</script></source>
What is going to happen if there is no exception handler
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="DivideByZero_aspx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
</form>
</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class DivideByZero_aspx : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { int i = 0; int j = 1; int k = j/i; }
}</source>