I have a provider which throws an exception which I want to handle where I read the provider:
@Riverpod(dependencies: [firebaseAuth])
User currentUser(CurrentUserRef ref) {
final user = ref.watch(firebaseAuthProvider).currentUser;
if (user == null) {
throw UserNotSignedInException();
}
return user;
}
and I want to catch it here:
try {
ref.read(currentUserProvider);
resolver.next();
} on UserNotSignedInException {
logger('User is not logged in, pushing intro route');
router.push(const IntroRoute());
}
But the Exception is thrown inside the provider and never reaches the catch block. Does somebody know how to pass the exception so I can handle it in the try catch? I know when using AsyncValue
that I get an AsyncError
to handle but I don’t want an async provider.
2
Answers
In my case it made most sense to just throw the Exception inside the try catch block. I want to do this because I want to make sure that a user is logged in and don't want to handle a nullable
User
object.You could wrap your
User
object inside anUserState
object with both theUser
and theException
orÈrror
.For example something like this:
And then in your code:
and
This way, your provider always returns a valid state, whether the
User
could be obtained or not.