hey everyone, need a bit quick help. pseudocode: W...
# server
t
hey everyone, need a bit quick help. pseudocode: When there is a “specialCase” error, throw the exception and Log this exception as “Info”. This is the if statement I have. Does this look like a good approach?
Copy code
if (error.contains (specialCase)) {
    throw specialCaseException
}
    <http://LOGGER.info|LOGGER.info>("logspecialCaseInfoAsInfo")
K 3
t
throwing an exception will jump out of the current function. If you want to log something in that "special case" the log statement should be inside the if-block and before the
throw
statement.
m
In general, you don’t want to throw and log n exception from the same site, you should do either one or the other. The ideal would be that when higher-level code handles exceptions it would log them in a centralized site. https://stackoverflow.com/a/6640029/255931
1
t
true in the vast majority of cases. Sometimes you have error handling on a higher level that will not log your exception. Then it could make sense to log something before throwing the exception. But then again, you're probably using exceptions for flow control or something like that, which is an anti-pattern in itself and your should consider restructuring.
t
Thanks for the input @Tobias Berger and @Matteo Mirk. To avoid anti-patterns from the SO article, will either of these two be sufficient?
Copy code
if (error.contains (specialCase)) {
    <http://LOGGER.info|LOGGER.info>("logspecialCaseInfoAsInfo")
    throw specialCaseException
}
OR
Copy code
if (error.contains (specialCase)) {
    throw specialCaseException.also {
        <http://LOGGER.info|LOGGER.info>("logspecialCaseInfoAsInfo")
    }
t
Basically both of those do the same, although the second one is more confusing and unnecessary (rule of thumb: don't use also/let if you don't use
it
inside) Anyways, this doesn't avoid the anti-pattern at all. You are logging something and then throwing an exception, which will usually also be logged somewhere else. So you should ask yourself why do you need the additional log? If there is information relevant to the error, why is it not included in the exception you're throwing?
m
they’re both examples of the described anti-pattern, please read the SO answers carefully