sandalone
sandalone

Reputation: 41749

A proper way to log and display error details?

I am aware that using printStackTrace() in Android apps should be avoided and we should use Log class.

Following this, I tried to log errors like this:

try {
   //do something  
} catch (Exception e) {
   Log.d(TAG, "General Exception:\n", e);
} 

and I got output like this:

Log level: Verbose
12-27 17:20:21.468: DEBUG/MyApp Page two fragment(11193): General IOException:

I did not get details on IOException.

Can somebody advise what I am doing wrong?!

Upvotes: 0

Views: 1342

Answers (5)

Vikalp Patel
Vikalp Patel

Reputation: 10877

Do these instead::

try {
 //do something  
    } 
catch (Exception e) {
    Log.e(TAG, "General Exception::"+e);
    } 

Upvotes: 0

QuokMoon
QuokMoon

Reputation: 4425

Log.v(); // Verbose
Log.d(); // Debug
Log.i(); // Info
Log.w(); // Warning
Log.e(); // Error

for more info

Log.e("error", String.valueOf(e.getMessage()));

Upvotes: 0

t0mm13b
t0mm13b

Reputation: 34592

There is no 3rd parameter!

If you read the sdk docs, android.utils.Log takes two parameters, this is general guideline as used:

  1. a tag identifying the message (can be usually defined as public static final String TAG="myActivity";
  2. A message, notice that this is a string so in your case it would need to be like this:
try {
   //do something  
} catch (Exception e) {
   Log.d(TAG, "General Exception:\n" + e);
} 

Notice the usage of the string concatenation operator.

Edit: To note: Log does have an overload which can indeed take the third parameter, but generally the method with two parameters is used, in respect to the third parameter, that is a Throwable as documented in the SDK. I rarely use it in my projects nonetheless as the method with two parameters is sufficient enough for my needs.

Upvotes: 1

the_marcelo_r
the_marcelo_r

Reputation: 1856

You are getting the generic Exception, a top-level object, avoid Pokemon exception handling (gotta catch 'em all) and catch the specific exceptions. But that's not the reason you are not seeing the exception details: try ioe.getMessage():

   try{
       startActivity( alertIntent );
   }catch(IOException ioe)
   {
       Log.e("error", "startActivity exception "+ ioe.getMessage());
   }

If you need to know the signature of the logging methods, just check the documentation: http://developer.android.com/reference/android/util/Log.html

For more details and ideas: http://blog.nelsondev.net/?p=187

Upvotes: 0

Budius
Budius

Reputation: 39836

do this instead:

  Log.d(TAG, e.getClass().getSimpleName() + ": " + e.getMessage());

Upvotes: 2

Related Questions