Reputation: 157
I am using the following code to handle Delete exceptions in my Formview. The trouble is I want to give the user a simple explanation should an error occur but I can't find a way to do so easily. I should say I'm new to ASP.NET. In the past I would have used an ERROR_NO to trap errors but I can't find the equivalent here. I can see that e.Exception.Message gives the error info but I can't give this to the user!...
EG: e.Exception.Message gives "The DELETE statement conflicted with the REFERENCE constraint "FK_users_offices". The conflict occurred in database "xyz", table "dbo.Users", column 'OfficeID'. The statement has been terminated."
Is there a way to identify this exception and trap it to display something like, "This Office cannot be deleted because dependent Users exists." for example?
My relevant code behind is:
protected void fv_OnItemDeleted(Object sender, FormViewDeletedEventArgs e)
{
if (e.Exception == null)
{
if (e.AffectedRows == 1)
{
lblMessage.Text="Record deleted successfully.";
}
else
{
lblMessage.Text = "An error occurred during the delete operation.";
}
}
else
{
lblMessage.Text=e.Exception.Message;
e.ExceptionHandled = true;
}
UserMessage.Visible = true; // Display Error message to user
}
Upvotes: 2
Views: 4796
Reputation: 14919
You may check the exception type and return messages to user according to exception type. Something like;
protected void fv_OnItemDeleted(Object sender, FormViewDeletedEventArgs e)
{
if (e.Exception == null)
{
if (e.AffectedRows == 1)
{
lblMessage.Text="Record deleted successfully.";
}
else
{
lblMessage.Text = "An error occurred during the delete operation.";
}
}
else
{
lblMessage.Text=e.Exception.Message;
if(e.Exception.GetType() == typeof(System.StackOverflowException))
lblMessage.Text = "Some stackoverflowexception occured, report to admin etc."
if(e.Exception.GetType() == typeof(System.ArgumentNullException))
lblMessage.Text = "Some argument exception occured"
e.ExceptionHandled = true;
}
UserMessage.Visible = true; // Display Error message to user
}
Upvotes: 1