0

I have a very simple question.

I made a Stored Procedure for my SQL and it looks like this:

    IF(@CurrentStatus='Fulfilled')
    BEGIN
        RAISERROR ('Opps, this item is too hot to last too long. It is SOLD OUT!',16, 1)
        RETURN -1           
    END

It will return a error message when the condition is meet.

In my C# code behind, I am using a try-catch block.

I simply want to display the error message from the above Stored Procedure to the screen. So which exception type I should use?

Here is my code:

            try
        {
            storeDB.AddToBuyingOrders(newOrder);
            storeDB.SaveChanges();
            TempData["Result"] = "Added";
            return View();
        }
        catch (SqlException ex)
        {
            TempData["Result"] = ex.InnerException.Message.ToString();
            return View();
        }

1 Answer 1

1

I wonder why do you ask question for that? You could catch Exception put a breakpoint in your code and got the answer within few seconds!!! It even took me less then five minutes to make working example just because I was curious about what problem is there that you don't do it yourselves.

Correct exception type to catch is EntityCommandExecutionException or its parent EntityException. The SqlException will be in its InnerException property and you will get your message there.

Sign up to request clarification or add additional context in comments.

2 Comments

I should use UpdateException, not EntityCommandExecutionException ... But still thank you for your help and your time.
What? If SaveChanges is in try block the exception will be handled in catch block. If it is not it means that it wasn't fired. Where do you actually use that procedure?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.