简体   繁体   中英

How to handle errors from Stored Procedure calls

I use a strored procedure to add a new order to the database but I can't find a way to handle exceptions/errors when I call the procedure in ASP.NET. Here is the code from the controller

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

And the try catch code from the procedure

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

The procedure works as well as its error handling. So the problem is how to catch the exception/error in the controller.

Figured it out I had to change the stored procedures error handling

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

And add this code to the controller

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

write try catch like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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