如何处理存储过程调用中的错误

时间:2018-12-28 10:16:58

标签: c# asp.net-mvc stored-procedures

我使用一个受约束的过程向数据库添加新订单,但是当我在ASP.NET中调用该过程时,找不到一种处理异常/错误的方法。 这是来自控制器的代码

public ActionResult Create(FormCollection collection)
{
    try
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        SqlCommand com = new SqlCommand("OrderAdd", con);
        com.CommandType = CommandType.StoredProcedure;
        com.Parameters.AddWithValue("@Cusid", collection["CustomerID"]);
        //More Parameters
        con.Open();
        com.ExecuteNonQuery();
        con.Close();
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

然后从过程中尝试捕获代码

    BEGIN CATCH
      SELECT ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_SEVERITY()
      ROLLBACK TRAN @AddTran
    END CATCH

该过程及其错误处理均有效。因此,问题在于如何在控制器中捕获异常/错误。

2 个答案:

答案 0 :(得分:0)

想通了 我不得不更改存储过程的错误处理

BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
        @ErrorMessage = ERROR_MESSAGE(),  
        @ErrorSeverity = ERROR_SEVERITY(),  
        @ErrorState = ERROR_STATE();  

    -- Use RAISERROR inside the CATCH block to return error  
    -- information about the original error that caused  
    -- execution to jump to the CATCH block.  
    RAISERROR (@ErrorMessage, -- Message text.  
               @ErrorSeverity, -- Severity.  
               @ErrorState -- State.  
               );   
    ROLLBACK TRAN @Tran
END CATCH

并将此代码添加到控制器中

catch (SqlException ex)
{
     System.Diagnostics.Debug.WriteLine(ex.Message);
     return RedirectToAction("Index");
}

答案 1 :(得分:-1)

写这样的try catch。

try
{
//block of code
}
catch (SqlException SqlEx)
{
//sql error handling
}
catch (Exception Exp)
{
//application error handling
}
finally
{
//optional
}