2

I have a generic question regarding to how to design error handling. I want to use some third-party service in my code. Normally I wrap the service within a client class. Then the rest of my code only deals with my client class and is blind to the real service under the hook. My client class has some mechanism to log errors. But it doesn't want to catch and deal any exception from the service. Ideally it should just ignore the exception handling and let the exception propagates to outside. However, if I want to log the exception, I have to do something like this:

try{
    .... // call 3rd party service;
}catch(Exception e){ // e is triggered from the service;
    Log.error("Oops, an error: " + e); // shall I log the exception??
    throw e; // don't swallow the exception;
}

On one hand, I don't want to do this. I can ignore the handling and logging of the exception. Let the caller of my client class handles exceptions or logs errors. The question is, when should I log exceptions and when should I not? I'd like to hear some common practice and principles. Thank you.

0

3 Answers 3

1

Don't log the exception at every level. Log it only at the "top" level. Log it at the point where not logging it would cause the exception to be missed.

Sign up to request clarification or add additional context in comments.

1 Comment

Simple guidelines. May not apply everywhere but it is the sort of things I am looking for.
0

That depends on you. My recommendations are to log the exceptions when they indicate something truly unexpected. Granted, the name "exception" would seem to indicate that this is always the case, but not necessarily.

Sometimes, code returns exceptions for scenarios that are unexeceptional.

Sometimes, code calls other code, knowing it will invoke exceptions in certain cases, but the set of exceptions is "OK".

Sometimes, an exception indicates something unexpected really did happen, and that's usually a bad thing. That's when you should log it, or better yet, make sure your code complains loudly.

Comments

0

If there is a fairly low chance of triggering the exception, I see no real reason not to log it. The only reason to not log an exception to help with debugging is if it is continually firing. If you have an exception that has this characteristic, then I suggest you write your code so that you don't have exceptions continually being triggered.

tl;dr: Exceptions are (hopefully) rare, so log them.

1 Comment

But log them where? In every method? I know that Java uses checked exceptions, so maybe it makes sense in Java, but it's a horrible idea in languages like C#.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.