Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

1stevengrant's avatar

Try/catch with Stripe API

Something that didn't occur to me before now on building this app is how to handle errors that don't come from my own code.

I have an AccountController that shows the users subscription status and a list of previous charges on Stripe.

However, when I logged in tonight, and it tried to pull from Stripe, their API had issues. Now I do have a try/catch statement

try {
           Stripe::setApiKey(env('STRIPE_SECRET'));

            $invoices = $user->invoices();

        } catch (\Exception $ex) {
            return $ex->getMessage();
        }

However, the returned message is just text. I wish to return that error to my view as well as give all the other data pertaining to account.

0 likes
3 replies
rawilk's avatar

You can return whatever kind of response you need to from the catch part, or even throw another exception if needed.

1stevengrant's avatar

thanks @wilk_randall - does that mean something like

session()->flash('alert', 'Looks like we have an issue here: '.$ex->getMessage());
return back();

would still show my user the rest of their account info but also show the error (assuming I'm handling that flash message in the view)?

Please or to participate in this conversation.