提供用户友好的异常消息

时间:2012-03-25 16:35:06

标签: c# asp.net sqldatasource formview

我使用以下代码处理Formview中的删除异常。问题是如果发生错误我想给用户一个简单的解释,但我找不到一种方法可以轻松地做到这一点。我应该说我是ASP.NET的新手。在过去,我会使用ERROR_NO来捕获错误,但我在这里找不到相应的错误。我可以看到e.Exception.Message提供错误信息,但我无法将此提供给用户!...

EG:e.Exception.Message给出“DELETE语句与REFERENCE约束冲突”FK_users_offices“。冲突发生在数据库”xyz“,表”dbo.Users“,列'OfficeID'。语句已经终止。“

是否有办法识别此异常并将其捕获显示类似“因为依赖用户存在而无法删除此Office”。例如?

我背后的相关代码是:

    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
    }

1 个答案:

答案 0 :(得分:1)

您可以检查异常类型并根据异常类型向用户返回消息。喜欢的东西;

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
}