[GH-ISSUE #119] Unable to catch SpotifyWebAPI\SpotifyWebAPIException #72

Closed
opened 2026-02-27 19:25:53 +03:00 by kerem · 4 comments
Owner

Originally created by @JohnGeorgine on GitHub (Apr 1, 2018).
Original GitHub issue: https://github.com/jwilsson/spotify-web-api-php/issues/119

The problem here seems kinda simple, yet I'm not being able to solve it.

I'm completely unable to catch exceptions from the API. I'm trying to catch it in order to verify if it's returning a 401 error (so I'll be able to know when the access token has expired and request a new one using the refresh token), but no matter what I do, I keep receiving the fatal error "Uncaught SpotifyWebAPI\SpotifyWebAPIException: The access token expired in...".

I've already tried to use:
"catch(SpotifyWebAPI\SpotifyWebAPIException $e)",
"catch(\SpotifyWebAPI\SpotifyWebAPIException $e)",
"catch(SpotifyWebAPIException $e)",
"catch(\SpotifyWebAPIException $e)",
"catch(Exception $e)" (this one borrowed from the own developer's example provided in https://github.com/jwilsson/spotify-web-api-php/blob/master/docs/examples/handling-errors.md),
and "catch(\Exception $e)",
but no matter what, nothing will do.

In all of the other issues submited here, the developer actually tried to solve the problem causing the Exception instead of dealing with the Exception itself, but the point is I actually have to deal with the Exception.

Any help will be deeply appreciated. Thanks in advance!

Originally created by @JohnGeorgine on GitHub (Apr 1, 2018). Original GitHub issue: https://github.com/jwilsson/spotify-web-api-php/issues/119 The problem here seems kinda simple, yet I'm not being able to solve it. I'm completely unable to catch exceptions from the API. I'm trying to catch it in order to verify if it's returning a 401 error (so I'll be able to know when the access token has expired and request a new one using the refresh token), but no matter what I do, I keep receiving the fatal error "Uncaught SpotifyWebAPI\SpotifyWebAPIException: The access token expired in...". I've already tried to use: "catch(SpotifyWebAPI\SpotifyWebAPIException $e)", "catch(\SpotifyWebAPI\SpotifyWebAPIException $e)", "catch(SpotifyWebAPIException $e)", "catch(\SpotifyWebAPIException $e)", "catch(Exception $e)" (this one borrowed from the own developer's example provided in https://github.com/jwilsson/spotify-web-api-php/blob/master/docs/examples/handling-errors.md), and "catch(\Exception $e)", but no matter what, nothing will do. In all of the other issues submited here, the developer actually tried to solve the problem causing the Exception instead of dealing with the Exception itself, but the point is I actually have to deal with the Exception. Any help will be deeply appreciated. Thanks in advance!
kerem closed this issue 2026-02-27 19:25:54 +03:00
Author
Owner

@JohnGeorgine commented on GitHub (Apr 1, 2018):

In case it's necessary, my code is:

<?php
require 'autoload.php';
require 'db.php';

if (isset($_GET['user']) && !empty($_GET['user'])) {
    try {
        $sth = $dbh->prepare('SELECT music_mode_access_token AS access, music_mode_refresh_token AS refresh FROM music_mode WHERE music_mode_username = ?');
        $sth->execute(array($_GET['user']));
        $token = $sth->fetch(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {
        $eMessage = 'Database error (code '.$e->getCode().'): '.$e->getMessage()."\n";
        $logFile = fopen("log.txt", "a") or die("Log error: unable to open log file.");
        fwrite($logFile, $eMessage);
        fclose($logFile);
        die($eMessage);
    }
}

if ((!isset($_GET['user']) || empty($_GET['user'])) || (!isset($token['access']) || empty($token['access']))) {
    header('Location: auth.php');
    die();
}

$api = new SpotifyWebAPI\SpotifyWebAPI();

try {
    $api->setAccessToken($token['access']);
} catch(Exception $e) {
    if ($e->getCode() == 401) {
        $session = new SpotifyWebAPI\Session(
            'CLIENT_ID',
            'SECRET_KEY',
            'PATH_TO/callback.php'
        );

        $session->refreshAccessToken($token['refresh']);
        $accessToken = $session->getAccessToken();
        $api->setAccessToken($accessToken);
    } else {
        $eMessage = 'Spotify Web API error (code '.$e->getCode().'): '.$e->getMessage()."\n";
        $logFile = fopen("log.txt", "a") or die("Log error: unable to open log file.");
        fwrite($logFile, $eMessage);
        fclose($logFile);
        die($eMessage); 
    }
}

// It's now possible to request data about the currently authenticated user
print_r($api->getMyCurrentTrack());
?>
<!-- gh-comment-id:377733668 --> @JohnGeorgine commented on GitHub (Apr 1, 2018): In case it's necessary, my code is: ```php <?php require 'autoload.php'; require 'db.php'; if (isset($_GET['user']) && !empty($_GET['user'])) { try { $sth = $dbh->prepare('SELECT music_mode_access_token AS access, music_mode_refresh_token AS refresh FROM music_mode WHERE music_mode_username = ?'); $sth->execute(array($_GET['user'])); $token = $sth->fetch(PDO::FETCH_ASSOC); } catch(PDOException $e) { $eMessage = 'Database error (code '.$e->getCode().'): '.$e->getMessage()."\n"; $logFile = fopen("log.txt", "a") or die("Log error: unable to open log file."); fwrite($logFile, $eMessage); fclose($logFile); die($eMessage); } } if ((!isset($_GET['user']) || empty($_GET['user'])) || (!isset($token['access']) || empty($token['access']))) { header('Location: auth.php'); die(); } $api = new SpotifyWebAPI\SpotifyWebAPI(); try { $api->setAccessToken($token['access']); } catch(Exception $e) { if ($e->getCode() == 401) { $session = new SpotifyWebAPI\Session( 'CLIENT_ID', 'SECRET_KEY', 'PATH_TO/callback.php' ); $session->refreshAccessToken($token['refresh']); $accessToken = $session->getAccessToken(); $api->setAccessToken($accessToken); } else { $eMessage = 'Spotify Web API error (code '.$e->getCode().'): '.$e->getMessage()."\n"; $logFile = fopen("log.txt", "a") or die("Log error: unable to open log file."); fwrite($logFile, $eMessage); fclose($logFile); die($eMessage); } } // It's now possible to request data about the currently authenticated user print_r($api->getMyCurrentTrack()); ?> ```
Author
Owner

@jwilsson commented on GitHub (Apr 1, 2018):

Hi!
Have you tried putting the try/catch block around the actual API call? Because it's that method that will actually throw an exception when you need to refresh the token. The $api->setAccessToken() call will never throw.

So the last line of your code should look like this:

// The rest of the code...

try {
  // It's now possible to request data about the currently authenticated user
  print_r($api->getMyCurrentTrack());
} catch (SpotifyWebAPI\SpotifyWebAPIException $e) {
  // Refresh the token if needed
}

BTW, I edited your comment and put the code in braces so it's easier to read. Hope that's alright!

<!-- gh-comment-id:377780436 --> @jwilsson commented on GitHub (Apr 1, 2018): Hi! Have you tried putting the `try/catch` block around the actual API call? Because it's that method that will actually throw an exception when you need to refresh the token. The `$api->setAccessToken()` call will never throw. So the last line of your code should look like this: ```php // The rest of the code... try { // It's now possible to request data about the currently authenticated user print_r($api->getMyCurrentTrack()); } catch (SpotifyWebAPI\SpotifyWebAPIException $e) { // Refresh the token if needed } ``` BTW, I edited your comment and put the code in braces so it's easier to read. Hope that's alright!
Author
Owner

@JohnGeorgine commented on GitHub (Apr 1, 2018):

OMG, that was it! It's fixed now! I feel so dumb but at the same time glad it worked, LOL. It took me a while to give a reply because I wanted to make sure everything was working properly, since right after the change I was getting a blank page for some reason. But now everything seems to be fine. I even made some tests by setting a custom message and a different API output for the "catch" block, so I'd know exactly when the key was expired and a new one was generated, and it all ran smoothly. Thank you and congrats for your API!

<!-- gh-comment-id:377821453 --> @JohnGeorgine commented on GitHub (Apr 1, 2018): OMG, that was it! It's fixed now! I feel so dumb but at the same time glad it worked, LOL. It took me a while to give a reply because I wanted to make sure everything was working properly, since right after the change I was getting a blank page for some reason. But now everything seems to be fine. I even made some tests by setting a custom message and a different API output for the "catch" block, so I'd know exactly when the key was expired and a new one was generated, and it all ran smoothly. Thank you and congrats for your API!
Author
Owner

@JohnGeorgine commented on GitHub (Apr 1, 2018):

BTW, that's okay with the braces. I'm new to GitHub, so I wasn't sure how to properly format my code. Thanks again!

<!-- gh-comment-id:377821488 --> @JohnGeorgine commented on GitHub (Apr 1, 2018): BTW, that's okay with the braces. I'm new to GitHub, so I wasn't sure how to properly format my code. Thanks again!
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/spotify-web-api-php#72
No description provided.