axdmoraes
axdmoraes

Reputation: 45

Custom exception. Where to log it

I created a CustomExceptionClass that its messages are from a configuration file and are a friendlier message to the user.

Then I want to log wich exception was thrown because, if something went wrong, I want to know details then I can fix this. So, I have a doubt.

Where to log these exceptions using log4j? Inside the CustomExceptionClass, or I let the method that throws this exception log it?

Upvotes: 1

Views: 2652

Answers (4)

jtoberon
jtoberon

Reputation: 9016

I'm not sure if you have a question about log4j in particular, but that API simply requires something to call log.error(Object,Throwable), passing in the message as the first parameter and the error as the second parameter. (log is of course a Log4J logger reference.)

Regarding the question of where to call log.error, do not call log.error from within your CustomExceptionClass subclass of Throwable. Instead, I'd make the decision as follows:

If you want to log details about exactly what happened, but you don't plan to put those details into your subclass of Exception, then log the details before throwing the error.

Similarly, if you want to log something specific regardless of whether or how the Exception is caught, then obviously you need to do this before throwing the Exception. You have relatively little control over who calls a non-private method.

Otherwise log in the catch block. This allows you to track both what happened and how your application responded as a result. If you just have the first piece of information, then other people will have to read the code in order to understand "so what?"

Finally, it's considered to be good practice to use uncaught exception handlers for all threads. See Thread.UncaughtExceptionHandler for more details. Basically you really want to at least log all Exceptions in long-running applications.

Upvotes: 3

Ioan Alexandru Cucu
Ioan Alexandru Cucu

Reputation: 12269

You should log it in the error handling code, not where the error is initially created.

Upvotes: 2

smp7d
smp7d

Reputation: 5032

You should log wherever you are catching the Exception. If you are not catching it anywhere it really depends how you are running your application.

Upvotes: 3

Will Chesterfield
Will Chesterfield

Reputation: 1780

I typically overload ToString and/or GetMessage in custom exceptions and simply log them per normal.

Upvotes: 1

Related Questions