Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to use an exception message property to check for particular error?

Sometimes the exception type is unique enough to indicate the exact issue, such as an ArgumentOutOfRangeException. Othertimes, the exception is more general and could be thrown for several reasons. In this scenario, it seems the only additional information is found in the exception message property.

In my current circumstance, I am getting a CommunicationException which throws the error message:

The maximum message size quota for incoming messages (65536) has been exceeded

As multiple different errors may be thrown via the CommunicationException, is it bad practice to use the message property to determine the cause, like so:

catch (CommunicationException ex)
{
    if (Regex.IsMatch(ex.Message, "The maximum message size quota for incoming messages .* has been exceeded"))
    {
        // handle thrown exception
    }
    throw;
}

Will these messages be constant and reliable on all systems? Are there any other considerations, such as localization?

Conclusion:

My scenario with the 'CommunicationException' was a bad example, as I later realized that there was a QuotaExceededException in the InnerException property. Thanks to the responses, I knew to look for any data that existed in the exception to indicate the exact cause. In this case, it was the InnerException property.

In terms of the question regarding whether or not the message property should be used to determine the cause, it seems to be the general consensus that it should be avoided unless there is no alternative. The message property value may not remain constant over varying systems due to localization.

like image 411
Luke Baulch Avatar asked Feb 21 '11 01:02

Luke Baulch


2 Answers

IMHO magic string solutions should always be a last resort.

Are you sure you can't resolve the type of the error from the additional properties on the CommunicationException object:

http://msdn.microsoft.com/en-us/library/system.servicemodel.communicationexception.aspx

.. or are you getting an InnerException that is more useful?

In answer to the last question, many .net exception messages are localized. So you might run into problems there if this software is going to be deployed widely. See the following question for a possible workaround for this:

Exception messages in English?

like image 152
James Gaunt Avatar answered Oct 16 '22 07:10

James Gaunt


Yes.

Normally the type of the Exception class (and maybe a property on it if custom exception class) should be what you check for.

If you deal with some framework or whatever that is badly written and you have no other way for sure (nothing in Data property or InnerException or anything), then, it's bad but you have to.

like image 22
Meligy Avatar answered Oct 16 '22 07:10

Meligy