The King
The King

Reputation: 4650

How to Catch Particular DB error in ASP.NET

In my SP (Sql Server 2005) I'm raising an error using

Raiserror ('No Records Fetched' , 16 ,1)

I want to catch this particular error in ASP.NET.. how do I do it ?

Upvotes: 0

Views: 151

Answers (2)

Ed Harper
Ed Harper

Reputation: 21505

Whilst Christian Hayter's answer is correct, an alternative would be to use sp_addmessage to create your own customer error number which relates specifically to this problem. This would save you having to parse the error message.

Upvotes: 0

Christian Hayter
Christian Hayter

Reputation: 31071

This ought to do it:

catch(SqlException ex) {
    if(ex.Errors.Count > 0 && ex.Errors[0].Message == "No Records Fetched" && ex.Errors[0].Class == 16) {
        // your error
    }
}

However, the errors collection may also contain low-severity print statement messages and other junk from previous statements. It's up to you whether you want to write more sophisticated filtering code to eliminate them.

Upvotes: 1

Related Questions