I'm calling to a Firebase method and in case of Exception I want to return the exception message in Spanish but task.getException().getMessage() is returning it in English instead.
Snippet code:
if (task.isSuccessful()) {
// do something
} else {
Toast.makeText(context, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
Do I have to change something in Firebase configuration?
Thanks in advance
You can throw the Exception returned by task.getException inside a try-catch-block. All the exeptions that are thrown are in english. Below, each type of Exception that may be thrown by the method you are using.
I have uses an example from the OnCompleteListener for the createUserWithEmailAndPassword() method. Please see the follwing code:
if(!task.isSuccessful()) {
try {
throw task.getException();
} catch(FirebaseAuthWeakPasswordException e) {
//do somethig
} catch(FirebaseAuthInvalidCredentialsException e) {
//do somethig
} catch(FirebaseAuthUserCollisionException e) {
//do somethig
} catch(Exception e) {
Log.e("TAG", e.getMessage());
}
}
Hope it helps.
getLocalizedMessage() does give you the description of the exception (the name is given by task.getException().getClass().getSimpleName()) but still in English (therefore with no difference from getMessage()).
In order to make use of its "localized" features, you first need to override the method according to your needs.
You can see a complete example of how to do that here, although for the simple purpose mentioned here, I would definitely stick with Alex's solution.
Related
In my current project I have a section where a user essentially enters a key to get the data under that key in firebase. I am using the get method as it only needs to be accessed once. The get method has an on Success and on failure listener and I have the entire thing within a try catch block but for some reason the app still bugs out and does a weird like crash and refresh action when a key that's not in the realtime database is entered. I ran a debug and for some reason when it reaches the get method in this situation instead of going to the catch block it leaves the function completely.
fun joinFinalised(newEmail: String, code: String) {
if (code.isEmpty()){
Toast.makeText(this, "No code entered", Toast.LENGTH_SHORT).show()
} else {
try {
fDBRef.child(newEmail.replace(".","~dot~")).get().addOnSuccessListener {
if (code == it.child("Code").value as String){
email = it.child("Email").value as String
fDBRef.child(email.replace(".","~dot~")).setValue(newCrew)
displayData()
}
}.addOnFailureListener{
Toast.makeText(this, "Join failed", Toast.LENGTH_SHORT).show()
}
} catch (e: Exception) {
Toast.makeText(this, "Join failed", Toast.LENGTH_SHORT).show()
}
}
}
The error it gives is java.lang.NullPointerException: null cannot be cast to non-null type kotlin.String which points to the line of the if statement where I compare the code.
I fixed the problem by adding a second try catch around the if statement where the error pointed to
I have a method which copies some files from shared memory to internal app memory using the library FileUtils.
The goal is handling IOException in order not to crash the app: it's acceptable if some files are not copied out of the total number.
In the second snippet below there is the called method where the exception is handled.
I need to know 2 things:
a) is there a way to handle the exception only in the called method
and not also in the calling code?
b) in your opinion the exception handling is correct or do I need to add some other code?
Below is the code:
try {
copyfilesfromshared(context);
} catch (IOException e) {
e.printStackTrace();
}
public void copyfilesfromshared(Context context) throws IOException {
for (int ii = 0; ii < numfiles; ii++) {
try {
FileUtils.copyFileToDirectory(files[ii], dirwrite);
} catch (IOException e) {
e.printStackTrace();
}
}
}
is there a way to handle the exception only in the called method and not also in the calling code?
If you handle the exception in copyfilesfromshared() function you do not need to declare throws IOException
public void copyfilesfromshared(Context context) {
for (int ii = 0; ii < numfiles; ii++) {
try {
FileUtils.copyFileToDirectory(files[ii], dirwrite);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Then you can use it normally, without declarin try {...} catch(...) again:
copyfilesfromshared(context);
in your opinion the exception handling is correct or do I need to add some other code?
This looks fine to me, but better check the signature of FileUtils.copyFileToDirectory if it throws any other exception as well, you maybe want to catch here too.
Beside that, it is totally on your side where you wanna handle the exception, but in general the earlier the better.
Heyy,
For your first question
a) is there a way to handle the exception only in the called method
and not also in the calling code?
There is a choise between throwing the IOException from the called method OR
to implement try/catch inside method.
And thats your problem
You are choosing both options instead of one, So just choose one.
And about 2 question
b) in your opinion the exception handling is correct or do I need to
add some other code?
Exception handeling is best at this moment, So don't think and other thought
And that's all!!
How to check for a specific exception, e.g. SocketException with message "Socket closed"? We can compare strings like this:
if (exception.getMessage().equals("Socket closed"))...
but is there some more elegant method, like comparing error codes, or comparison with constant exception value?
Except if SocketException is always "Socket closed", but in docs it states that this class is a superclass for all socket exceptions, so there is more than one.
UPDATE:
I don't want to check for exception class. If I do, I would use specialized catch rather than to check tor a class explicitly:
catch (SocketException ex) { ... }
I want some more elegant method to distinct two exceptions which are instances of the same class, not by comparing strings like this:
try {
int i = 2;
if (i == 1) throw new SocketException("one");
else if (i == 2) throw new SocketException("two");
}
catch (SocketException ex) {
if (ex.getMessage().equals("one")) { ... }
}
In this particular case I throw exceptions to show what is it about, but in reality it can be code not controlled by me.
Also I noticed that exception message in one particular case method threw "Socket closed", in another different method threw "Socket is closed". So it's not so reliable to stick to the message either.
Your question has different approaches, depending on what you are trying to achieve. The simplest method for determining if you have the exception you want is to use instanceof since an Exception is a class as well, i.e.:
if (myException instanceof SocketException) {
...
}
However, you then add the requirement of the contents of the message or the possibility that the Exception thrown is actually a subclass of the Exception of interest to you. In the case of a "subclass" you can check if it is a subclass with:
if (myException instanceof SocketException &&
myException.getClass() != SocketException.class) {
// then I'm an instance of a subclass of SocketException, but not SocketExcpetion itself
}
Or conversely, only evaluate for the parent class:
if (myException instanceof SocketException &&
myException.getClass() == SocketException.class) {
// then I'm an instance of the class SocketException, and not a cubclass of SocketExcpetion!!
}
These serve as the "error codes" you seem to be looking for - the identification of the class, with certainty.
However, if you really are interested in the human-readable error contents, then the solution you have should be your implementation. That seems unlikely, but sometimes that is what is required.
You can use:
exception.getClass().getSimpleName() and compare it to SocketException
Hope this helps.
guys what are the best alternatives for Error Handling in android.
All in all I dont want my application to shutdown in first attempt.
Say it started, made a http request, error and closed.
I am looking for a warning type error and let it continue further functionality.
Thanks in advance.
when trying to print a stack trace you should always use this:
try {
// DO STUFF
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e);
}
Try Log.e(String, String);
Should work for you
try {
//Code
} catch (Exception e) {
System.out.println(e);
}
I have some piece of code. In that there are chances to get many number of exceptions. My doubt is, to handle all those exceptions do i have to write catch blocks for each type of exception. Is it an efficient way or not. Except using throws keyword, If any other solutions are there please suggest me to do that. Any response will be appreciated.
Thanks in advance
It depends on what kind of exceptions you're trying to catch. Everything that can be thrown implements Throwable, so you can catch everything with
} catch (Throwable t) {
including run time errors and all. As Amjad mentions, you can narrow that a little with
} catch (Exception e) {
which just catches Exception and its subtypes.
The problem with both of these is that they catch too much; you can work around that but you risk catching an important problem and then not handling it.
If you have just a few different exceptions, you're probably best off with an exception comb
} catch (Exception1 e) { // do something
} catch (Exception2 e) { // do something else
You have one other option if these are your own exceptions: make a class hierarchy of your own exceptions
class MyExceptions extends Exception { /* ... */ }
class MyExceptionSubtypeA extends MyException { /* ... */ }
class MyExceptionSubtypeASubsub1 extends MyExceptionSubtypeA { /* ... */ }
Now you can pick any subtree of classes, as with
} catch (MyExceptionSubtypeA sa) {
which will catch both MyExceptionSubtypeA and MyExceptionSubtypeASubsub1.
Use the general kind of exception Exception
try{
//your code here
}
catch(Exception e){
//handle exception
}
However this is unrecommended http://source.android.com/source/code-style.html#exceptionsAll