繁体   English   中英

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

[英]How to handle errors from Stored Procedure calls

我使用一个受约束的过程向数据库添加新订单,但是当我在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

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

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

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

像这样写try catch。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM