ASP.NET Tutorial/Development/Exception — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 11:56, 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 Use Global.asax to log application level exception
- 9 What is going to happen if there is no exception handler
Application-level error handling
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
Catch exception and display exception message, Source and StackTrace (C#)
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">
<div>
<asp:Label ID="Label1" runat="server" Text="A:"></asp:Label>
<asp:TextBox ID="txtA" runat="server">5</asp:TextBox><br />
<asp:Label ID="Label2" runat="server" Text="B:"></asp:Label>
<asp:TextBox ID="txtB" runat="server">0</asp:TextBox><br />
<br />
<asp:Button ID="cmdCompute" runat="server" OnClick="cmdCompute_Click" Text="Divide A / B" /><br />
<br />
<br />
<asp:Label ID="lblResult" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label></div>
</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 = "<b>Message:</b> " + err.Message;
lblResult.Text += "<br /><br />";
lblResult.Text += "<b>Source:</b> " + err.Source;
lblResult.Text += "<br /><br />";
lblResult.Text += "<b>Stack Trace:</b> " + err.StackTrace;
lblResult.ForeColor = Color.Red;
}
}
}
Divide By Zero With Exception
<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>
Generic error handler page
<%@ 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">
<div>
<table>
<tr>
<td>
An <strong>unrecoverable</strong> error occurred and we"re still investigating the
reasons.<br />
<b>Error code: </b><span runat="server" id="ErrorCode"></span><br />
<b>Error path: </b><span runat="server" id="Referrer"></span>
</td>
</tr>
</table>
</div>
</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 = "<i>No error information available.</i>";
object o = Request.QueryString["ErrID"];
if (o != null)
errCode = (string) o;
ErrorCode.InnerHtml = errCode;
string referrer = "<i>Error path not available.</i>";
string temp = Request.UrlReferrer.ToString();
if (!String.IsNullOrEmpty(temp))
referrer = temp;
Referrer.InnerHtml = referrer;
}
}
Page-level error handling
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
Transfer to different page based on exception type
<%@ 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.
<div id="pageContent">
<form id="form1" runat="server">
<ul><li>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">Click to throw a NotImplementedException exception</asp:LinkButton>
</li><li>
<asp:LinkButton ID="LinkButton2" runat="server" OnClick="LinkButton2_Click">Click to generate an internal error</asp:LinkButton></li>
<li>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="missing.aspx">Click to raise a HTTP 404 error</asp:HyperLink></li>
</ul>
</form>
</div>
</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());
}
}
Try to catch error when converting text value to number
<%@ 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">
<div id="container">
<h1>Simple Calculator</h1>
<div class="box">
<asp:TextBox ID="txtValue" runat="server" />
<br />
<asp:Button Text="Do Math" runat="server" ID="btnDivide"
OnClick="btnDivide_Click" />
</div>
<asp:Label ID="labMessage" runat="server" />
</div>
</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";
}
}
}
Use Global.asax to log application level exception
<%@ 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>
What is going to happen if there is no exception handler
<%@ 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">
<div>
</div>
</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;
}
}