The Page_Error() event, exposed by the Page object, can be used to catch errors on a
page level.The following code demonstrates how you can use this event for page level
error handling.
In <script runat="server" /> block or codebehind:
Private Sub Page_Load(Source As Object, E As EventArgs)
Dim _Connection As New
➥SqlConnection("Server=localhost;Database=pubs;uid=sa;pwd=;")
Dim _Command As New SqlCommand("Select * From Authors", _Connection)
'_Connection.Open() causes an exception
DG1.DataSource = _Command.ExecuteReader(CommandBehavior.CloseConnection)
DG1.DataBind()
_Connection.Close()
End Sub
Public Sub Page_Error(Source As Object, E As EventArgs)
Response.Write(Server.GetLastError.ToString())
Server.ClearError()
End Sub
Comments
The demonstrated code tries to execute a query without having an open connection to
the datasource.This raises an exception, which is captured by the Page_Error() event of
the Page object itself.Within the Page_Error event, the code displays the error message
by calling the GetLastError method of the Server object.This returns an exception
object that is generated by the error. Note that the data access technique used in this
code is not a good approach for connecting to datasources; it has been adopted here
only for demonstrating the Page_Error event.You should always use the
Try/Catch/Finally statements for interacting with datasources.
Errors can also be handled at the application level using the Application_Error
event found in global.asax.
No comments:
Post a Comment