【问题标题】:How to handle errors from Stored Procedure calls如何处理来自存储过程调用的错误
【发布时间】:2018-12-31 04:50:01
【问题描述】:

我使用存储过程向数据库添加新订单,但在 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

该过程及其错误处理同样有效。所以问题是如何在控制器中捕获异常/错误。

【问题讨论】:

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


【解决方案1】:

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

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");
}

【讨论】:

    【解决方案2】:

    这样写try catch。

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

    【讨论】:

    • 那些用减号评价这个答案的人必须知道正确的答案。如果是,请在此处发布。如果没有,请不要评价它。
    猜你喜欢
    • 1970-01-01
    • 2020-04-13
    • 2019-12-22
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 2022-01-04
    • 2020-03-08
    • 1970-01-01
    相关资源
    最近更新 更多