Link to home
Start Free TrialLog in
Avatar of dotnet0824
dotnet0824

asked on

Catch Error and Rethrow with sensible message

SQL Server 2005 / C#.NET
Hi I have a stored procedure in SQL Server 2005 with Error Handling... Lets say user passes CustomerID Number 2 to be deleted. Then I will get a Foreign key violation in RaiseError. Now i want to Catch that Error message Format it and send back to my client from my Class...  How can I format the Original message being thrown, Modify it and rethrow it back again.

Create Procedure Delete_Customer
@Cust_ID int
As
BEGIN TRY
Delete from Customer where customer_ID =@Cust_ID
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
SELECT @ErrorMessage = ERROR_MESSAGE();
RAISERROR (@ErrorMessage, 16, 1);
END CATCH
Avatar of RedKelvin
RedKelvin

Hi there, try this

            try
            {
                int x;
                int y = 0;
                x = 1 / y;
            }
            catch (DivideByZeroException ex)
            {
                throw new DivideByZeroException("My custom message " + ex.Message);
            }

Open in new window

Avatar of dotnet0824

ASKER

Whatz that.. did u read my question
yes I did read your question, you want to catch an error and rethrow it with a custom message, if you read my code, you will see that is what is happening, you can ignore the divide by zero, I was just using that so that you could see that it is working
Avatar of multithreading
Given that you are on Sql 2005, you could use .Net for your procedure. Then you could have complete control over the try/catch. It would be more work than the "i wish it were like this" psuedo code you wrote, but after registering the DLL in SQL 2005 it would get you were you are trying to go.
ASKER CERTIFIED SOLUTION
Avatar of imitchie
imitchie
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
can we use Varchar(MAX) instead of DECLARE @ErrorMessage NVARCHAR(4000)
RedKelvin:yes I did read your question, you want to catch an error and rethrow it with a custom message, if you read my code, you will see that is what is happening, you can ignore the divide by zero, I was just using that so that you could see that it is working

You were saying about DivideByZero exception...being caught @ client. But in my case how can I use the same technique @ the client.....
yes varchar(max) will be fine for most standard installations. although i can't imagine you wanting to stuff more than 4000 bytes as an error message.  nvarchar is good for multi-byte system, but i don't think that applies to you