如何在我的asp.net mvc中捕获SqlException错误

时间:2013-01-05 22:14:32

标签: sql-server asp.net-mvc entity-framework

我有以下行动方法:

[Authorize]
    public ActionResult CustomersDetails(long[] SelectRight)
    {
        if (SelectRight == null)
        {
            return RedirectToAction("customer", new { isError = true });
        }
        else
        {
            try 
            {
                var ContactsDetails2 = new ContactsDetails
                    {
                        Info = r.getcontactinfo(SelectRight)
                    };

                foreach (var x in ContactsDetails2.Info)
                {
                    ViewData[x.USER_ID.ToString()] = r.getorgname(x.USER_ID).ToString();
                }

                return View(ContactsDetails2);
            }
            catch (SqlException)
            {
                ModelState.AddModelError("", "Too many records will be returned, please try to minimize your selection and try again.");
                return RedirectToAction("customer", "Home");
             }
         }            
      }

和以下方法:

public IEnumerable<AaaUserContactInfo> getcontactinfo(long[] id)
        {
            var organizationsiteids = from accountsitemapping in entities.AccountSiteMappings
                      where id.Any(accountid => accountsitemapping.ACCOUNTID == accountid)
                                       select accountsitemapping.SITEID;
//code goes here

现在,如果getcontactinfo引发了以下异常: -

  

[SqlException(0x80131904):SQL语句的某些部分是嵌套的   太深了重写查询或将其分解为较小的查询。]   System.Data.SqlClient.SqlConnection.OnError(SqlException异常,   Boolean breakConnection,Action`1 wrapCloseInAction)+388
  System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject   stateObj,Boolean callerHasConnectionLock,Boolean asyncClose)+688
  System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,   SqlCommand cmdHandler,SqlDataReader dataStream,   BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject   stateObj,布尔&amp; dataReady)+4403
  System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()+82
  System.Data.SqlClient.SqlDataReader.get_MetaData()+135

.... **catch (SqlException)**无法到达?

1 个答案:

答案 0 :(得分:1)

catch (SqlException)更改为catch (Exception ex)

SqlException发生之前,您可能会遇到另一种异常。