Are Dynamic Exception Messages a Good Idea?

254 views Asked by At

I'm designing an infrastructure for a project and I've been wondering if it'd be a good idea to format the exception's message with parameters, making it dynamic.

This means, on the one hand, that exception messages can be really verbose.

The downside, which is a lot stronger, in my opinion, is that you can't expect certain messages. These can be used (though it's not a best-practice) in exception handling, testing whether the message is this or that and in logging. But what's even more disturbing is that it will make localization a lot harder if you intent on showing that message somewhere (which I do).

So my question is what's your take on it and whether you have a compromising solution, giving me both verbosity (in case I log the exception) and consistency.

Thanks.

1

There are 1 answers

3
yankee On BEST ANSWER

I believe that including parameters in Exceptions is often extremely helpful. Think about that other developers (and you yourself) will read the message and try to find a bug. Or even worse: A user may read an exception message to you or post it on a forum and you have to find out what's wrong remotely.

Testing for certain messages in exceptions is indeed not best practice. I'd call it bad practice. All languages I know allow you to define our own Exception classes and also add custom properties to the class if the pure class name is not good enough for you (though it usually is). I believe messages in Exceptions should be as human readable as possible and there is no need for them to be predictable by code.

Of course you can overdo anything. Exception messages should not grow too large/long just because you wanted to include all possible variables in it. Select wisely ;-).