Exception identifier

  • Thread starter Thread starter John
  • Start date Start date
J

John

Hi all, I have a question about capturing exception details in C#.

Is it possible to query the exception and get an id related to what caused
the exception??

e.g

1 = Tried to enter a row into a database but there was a Primary Key
conflict

Currently I am doing something like this

catch(Exception ex){
if (ex.Message.ToString().ToLower().IndexOf("primary key")>0){

But this looks decidely suspect so if anyone knows of a better way, I am all
ears ;)

Thanks
Mark
 
John said:
Hi all, I have a question about capturing exception details in C#.

Is it possible to query the exception and get an id related to what caused
the exception??

e.g

1 = Tried to enter a row into a database but there was a Primary Key
conflict

Currently I am doing something like this

catch(Exception ex){
if (ex.Message.ToString().ToLower().IndexOf("primary key")>0){

But this looks decidely suspect so if anyone knows of a better way, I am all
ears ;)

Thanks
Mark

Define your own exception class derived from Exception like this:
class MyException: Exception
{
int ErrCode;
MyException(int err, string msg): base(msg)
{
ErrCode = err;
}
}

Something like that. And when you catch the exception, you know the err code and explanation.

catch (Exception ex)
{
if (ex is MyException)
if (((MyExcption)ex).ErrCode = 5)
{...do whatever...}
}

Hope it helps
Andrey
 
Is it possible to query the exception and get an id related to what caused
the exception??

If its a SqlException you're catching, you can get plenty more
information from the Errors property (a collection of SqlError, which
have a numeric Number property).




Mattias
 
Back
Top