As an Android Studio user, you should be familiar with the “surround-with try-catch” functionality.
When you use Ctrl+Alt+T(Linux) / Cmd+Alt+T(Mac) shortcut, the built-in try-catch generator auto generates a call to the printStackTrace() method of class Exception in the catch block. After this, we manually add some code to log the exception.
e.g.,
As a power user, you may have used some or all of the following built-in Live templates:
You can save yourself the pain of these 5-keystrokes or repetitive typing or copy pasting the code by becoming a Ninja who uses a custom built-in try-catch template.
Step-2: Select Code | Catch Statement Body
Step-3: Replace the existing template from:
I generally use the following template, which logs the error using Timber and records the exception on Crashlytics.
Surround with try-catch |
When you use Ctrl+Alt+T(Linux) / Cmd+Alt+T(Mac) shortcut, the built-in try-catch generator auto generates a call to the printStackTrace() method of class Exception in the catch block. After this, we manually add some code to log the exception.
e.g.,
Log.e(TAG, “Oops! something gone wrong”, e);
As a power user, you may have used some or all of the following built-in Live templates:
Live Templates |
You can save yourself the pain of these 5-keystrokes or repetitive typing or copy pasting the code by becoming a Ninja who uses a custom built-in try-catch template.
Steps for customization
Step-1: Go to Android Studio Preferences | Editor | File and Code TemplatesStep-2: Select Code | Catch Statement Body
Step-3: Replace the existing template from:
${EXCEPTION}.printStackTrace();with:
Log.e(getClass().getSimpleName(), "Exception logged", ${EXCEPTION});
I generally use the following template, which logs the error using Timber and records the exception on Crashlytics.
Timber.e(${EXCEPTION}, "Failed with %s", ${EXCEPTION}.getClass().getSimpleName()); Crashlytics.log(${EXCEPTION}.getMessage());
Sample Preview
Preview showing the usage customized try-catch template |
Comments
Post a Comment