rinukkusu / spotify-dart

A dart library for interfacing with the Spotify API.
BSD 3-Clause "New" or "Revised" License
207 stars 93 forks source link

Added static async factory to SpotifyApi to catch exceptions thrown by oauth2 package #122

Closed evaqum closed 2 years ago

evaqum commented 2 years ago

Right now the only way to instantiate SpotifyApi class with credentials is like this:

var credentials = SpotifyApiCredentials(
  'clientId',
  'clientSecret',
);
var spotify = SpotifyApi(credentials);

But with wrong credentials you get AuthorizationException, which you can't catch with any obvious way (and probably can't catch without modifying the library itself at all)

try {
  var spotify = SpotifyApi(invalidCredentials);
} on AuthorizationException {
  print('This will never print despite the exception being thrown');
}

That is because _getOauth2Client method never gets awaited and is instantly used in class. https://github.com/rinukkusu/spotify-dart/blob/7af8323ebe3831fac1ac8beb72aa5c991728f827/lib/src/spotify_base.dart#L54-L56

However, this PR allows instantiating SpotifyApi asynchronously with static method asyncFromCredentials, meaning that exceptions can be handled in <Future>.catchError or a try/catch block.

try {
  var spotify = await SpotifyApi.asyncFromCredentials(invalidCredentials);
} on AuthorizationException {
  print('Invalid credentials!');
}

I also added export from oauth2 package exposing AuthorizationException and ExpirationException so these can be handled

Might resolve #73

rinukkusu commented 2 years ago

Hmm, I think I've either done something wrong while trying to get your branch up-to-date (so I could merge it), or Github doesn't behave well with merge conflicts...

Could you maybe reset your branch to your own commit and then try to rebase/merge with this master yourself?

Thanks and sorry for reacting so late!!

evaqum commented 2 years ago

I think I did it? Hope I didn't mess up

upd: okay I actually messed up

evaqum commented 2 years ago

Now everything should be fine (I really hope so!)