Reputation: 562
I'm making an http call that will either return a 200, 412 or 403 statusCode. If it returns an error code, I'll throw an exception
if(response.statusCode == 412){
throw InvalidCredentialsException();
}
else if(response.statusCode == 403){
throw SalesManUnregisteredException();
}
else{
throw ServerException();
On the repository implementation, i need to catch the error so I can return the appropriate failure response
try {
//code
}
catch (e){
if(e == InvalidCredentialsException())
return InvalidCredentialsFailure();
else if(e == SalesManUnregisteredException())
return SalesManUnregisteredFailure();
else
return ServerFailure();
}
When I print the vars
print(e) //Instance of InvalidCredentialsException
print(InvalidCredentialsFailure()) //Instance of InvalidCredentialsException
But when I compare it, it returns false
print(e == InvalidCredentialsFailure()) //false
How can I equate these same instances so I can return the failure class according to the exception thrown?
Upvotes: 0
Views: 174
Reputation: 31299
If you want to handle different types of exceptions you should use the on
keyword to specify which type you want to catch:
try {
//code
} on InvalidCredentialsException catch (e) {
return InvalidCredentialsFailure();
} on SalesManUnregisteredException catch (e) {
return SalesManUnregisteredFailure();
} catch (e) {
return ServerFailure();
}
The last catch
will catch all other exceptions if another catch could not be found.
And just for info, if you want to compare the type of a object you should use the is
keyword like (e is SalesManUnregisteredException)
.
Upvotes: 2