1. Original Entry + Comments2. Write a Comment3. Preview Comment
New comments for this entry are disabled.

May 08, 2006  |  Error handling in data source controls  |  8215 hit(s)

In a comment on another post about validating parameters for the SqlDataSource control, someone asks about how to handle errors that might occur within the SqlDataSource control -- e.g. "query timeout, SQL Server not running, mistake in query," to quote the comment. I thought it was worthwhile to promote the discussion from the comments to a separate entry. (If you read those comments, there's nothing new here for you ...)

Eilon confirmed that the data source controls don't raise their own error events. You can trap errors like the ones listed, but you have to do so slightly indirectly.

You have (at least) two choices. One is to perform data binding yourself and put the DataBind call into a try-catch block:
Sub Page_Load()
If Not IsPostBack Then
GridView1.DataSourceID = "SqlDataSource1"
Catch ex As Exception
' Hopefully better error handling that this ...
Response.Write("Error data binding")
End Try
End If
End Sub
You can also catch the error in the Page_Error handler (documented here). Handle the Page_Error event and then redirect (using Server.Transfer) to an error page. Here's the handler:
Sub Page_Error()
End Sub
And a possibility for the target page:
Sub Page_Load()
Label1.Text = Server.GetLastError.Message
End Sub
This will catch all unhandled errors in the page, which I guess is a good thing or a bad thing, depending.

PS You can also create an application-level error handler. (#)

Zubair.NET!   08 May 06 - 10:45 PM

Is there a way to trap errors -- when you are using the DataSource Controls in your page with inline SQL query and bind your Databind controls to them?

mike   08 May 06 - 10:49 PM

You should be able to use the Page_Error handler, no? The data source controls will not individually allow you to trap errors. However, as noted, if you are calling DataBind explicitly, you can catch errors in an exception handler.

Tim L.   05 Jul 07 - 12:24 PM

I may not understand the nature of the question, but I have no trouble handling SQL errors with the SqlDataSource's OnSelected Event, such as in the following:
private void SqlDataSource_Selected(object sender, SqlDataSourceStatusEventArgs e)
// handle any SQL errors
if (e.Exception != null)
LabelSQLError.Text = e.Exception.Source + ": " + e.Exception.Message;
LabelSQLError.Visible = true;
e.ExceptionHandled = true;