[英]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.