问题
In my application, I want to send logs in case of crash to remote server. I have added try-catch block and in catch I'm sending logs to server. I want to know what all exceptions should I catch. I need logs in case of every crash so that I can fix it. Would it be a good practice to catch all Exceptions?
Thanks in advance.
回答1:
Here is a summarized list of suggestions I curated from other great answers:
Catch all unhandled exceptions.
Create an
ExceptionHandler
that implementsjava.lang.Thread.UncaughtExceptionHandler
. You can use this class to customize and log errors.Put this:
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this));
insideOnCreate()
method (aftersuper()
) of each of yourActivity
class .For details, please refer to this great answer from Android exception handling best practice .
Enclose try/catch around all codes that run externally/from outside. (e.g - codes using 3rd party components)
Enclose try/catch around all codes that you know, can fail on certain conditions
- When there is no internet connections
- During I/O Operations
- When there is potential for crazy user inputs
- When there is potential for divide by zero situations
Use try/catch at the top level because all exceptions are bubbled up to the top level. So, in inner functions, if need be, you can consider using
throw
exception. Then, at the top level, catch specific exceptions and sort your exception types in catch block correctly. (Referred from this great answer: How using try catch for exception handling is best practiceFor UI, you should offer "continued usability" by providing "limited functionality" version of the app even if the error occurs (if the error is due to, for example, no internet connectivity).
Over-eager error reporting to user is not a good idea.
Persistent error messages are bad. Inform user with a message and let the user close/remove it.
Reference 1 | Reference 2 | Reference 3 | Further Reading 1 | Further Reading 2 | Further Reading 3
For an Android library to remotely log unhandled exceptions, you can take a look at this: android-remote-stacktrace .
- Download .jar file.
- Add it to Java Build path.
Add INTERNET permission: uses-permission android:name="android.permission.INTERNET"
In the
OnCreate
method of your activity or service, put 'ExceptionHandler.register(this, "http://your.domain/path");'- On your server, place this PHP file, which you can edit to extend the functionality.
回答2:
You can use Crashlytics or Bugsense
https://mint.splunk.com/
https://try.crashlytics.com/
来源:https://stackoverflow.com/questions/31421865/how-to-send-android-app-logs-to-remote-server