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

Fioreski's avatar

How best to throw exceptions in a try catch

Hi Laravel community,

PLease could I get some advice for the following:

public function createPaymentIntent($id)
    {
        try {
            $user = User::find($id);
            return response($user->createSetupIntent(), 201);
        } catch (Throwable $error) {
            report($error);
            return response(throw new UnprocessableEntityHttpException("There was a problem setting up your subscription, please contact us if the problem persists."), 400);
        }
    }

I am trying to start to integrate stripe, does the above make sense when handling errors??

Is there a better way to write this out? Even a link to some documentation or an article would be great of you do not have the time to give an example.

Many thanks

0 likes
8 replies
Sinnbeck's avatar

You either throw an exception or return a response. Not both

return response("There was a problem setting up your subscription, please contact us if the problem persists.", 400);
Fioreski's avatar

@Sinnbeck many thanks for the speedy response, may I ask what would be your preference to return?

mabdullahsari's avatar

@Fioreski It depends on the context. If it is some kind of Service class, you should throw an Exception and handle it in the ExceptionHandler.

If it is something that happened in the outer edges of your application, you can return a Response.

There is no right and wrong, depends on how you want to organize things.

Fioreski's avatar

@mabdullahsari It is currently in a controller so if it fails I need to let the front end now so it can display the appropriate message to the end user so I assume it will be n exception in this instance?

mabdullahsari's avatar

@Fioreski You can convert the exception to a user-facing error if you can do that. For example if they submit a form, you can convert the Domain exception into a Validation exception so the user has some visible feedback without having your entire app crash. So, it won't even reach the ExceptionHandler.

mabdullahsari's avatar
Level 16

@Fioreski

try {
    $service->doSomething();
} catch (SomethingHorribleHappenedException) {
    throw ValidationException::withMessages([
        'error' => 'Something bad happened. Please try again later'
    ]);
}

An example 👆

1 like

Please or to participate in this conversation.