【问题标题】:c# LinqToSql exception handling when database is offlinec# 数据库离线时的LinqToSql异常处理
【发布时间】:2017-11-23 18:22:20
【问题描述】:

使用 Linq to Sql 构建 C# MVC Web 应用程序以查询 SQL 数据库。 如果数据库应该脱机以避免黄屏死机,我正在尝试捕获异常。

经过调试,我发现了两件事。首先,DataContext的创建并没有检查sql server是否可用。其次,在 rows 变量中存储了一条错误消息(或异常!?)。

永远不会到达下面代码中的 Catch 语句。所以当我试图从视图中的模型读取数据时,我得到了黄屏死机。

为什么没有到达 Catch 语句?

代码:

        try
        {
            //Creating DB Context
            var con = ConfigurationManager.ConnectionStrings["teststring"].ConnectionString;
            TestDataContext db = new TestDataContext(con);

            //Querying database. This should cause an exception to be thrown!?
            var rows =  from s in db.Table
                        orderby s.Id descending
                        select s; 

            //Returning the View with the data
            return View(rows);
        }
        catch (Exception ex)
        {
            ErrorInfo err = new ErrorInfo("Something went wrong when trying to query the database. See the log for details.");
            err.WriteToErrorLog(ex);
            return View("Error", err);
        }

【问题讨论】:

  • 由于延迟执行,对 db 的实际调用在视图中。你必须先实现它。添加.ToList() 并向视图发送列表。
  • 谢谢@OfirWinegarten。这应该是公认的答案。

标签: c# model-view-controller linq-to-sql exception-handling


【解决方案1】:

你尝试过使用 SQLException

try
    {
        //Creating DB Context
        var con = ConfigurationManager.ConnectionStrings["teststring"].ConnectionString;
        TestDataContext db = new TestDataContext(con);

        //Querying database. This should cause an exception to be thrown!?
        var rows =  from s in db.Table
                    orderby s.Id descending
                    select s; 

        //Returning the View with the data
        return View(rows);
    }
    catch (SqlException ex)
    {
        ErrorInfo err = new ErrorInfo("Something went wrong when trying to query the database. See the log for details.");
        err.WriteToErrorLog(ex);
        return View("Error", err);
    }

【讨论】:

    【解决方案2】:

    首先:正如@ofir 所说,您应该调用.ToList() 方法来执行LINQ 语句。所以你应该在你的 try 块上调用它来捕获异常。

    其次: 由于安全原因,您不应向最终用户显示黄色错误屏幕,您可以在web.config 文件中启用 CustomError 以在引发异常时显示默认页面并将其重定向到错误页面

    <customErrors mode="On" defaultRedirect="~/ErrorPages/GeneralError">      
    </customErrors>
    

    【讨论】:

      猜你喜欢
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多