Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Throwing response exceptions conditionally in Laravel 8.x

When you’re using Laravel’s Http client to make Http requests and something went wrong from the server-side, the server would return one of the error reponses such as 500 Internal Server Error, 502 Gateway Timeout, and so on.

Now, Laravel already comes with a method called throw() that you can call on the response instance if there are any client or server errors. The method would throw an instance of Illuminate\Http\Client\RequestException in such a scenario.

$response = Http::post('http://test.com/user/add', [
    'name' => 'Steve',
    'role' => 'Network Administrator',
]);

// Throw an exception if a client or server error occurred...
$response->throw();

return $response;

This is pretty alright but what if you want to throw this exception conditionally? For instance, you would only want to throw exceptions in the production environment. How would you do that?

Well, this is where this new method called throwIf(), which is added in the recent release of Laravel, comes into the picture.

The throwIf method

This PR in Laravel 8.x adds a method called throwIf() which is exactly the same way as the throw() method but with an added advantage of throwing exception conditionally.

So, if you want to throw exceptions only in the production environment in the previous example, here’s how you can do it using the throwIf() method.

$response = Http::post('http://test.com/user/add', [
    'name' => 'Steve',
    'role' => 'Network Administrator',
]);

$production = app()->environment('production');

// Throw an exception if when in production environment
$response->throwIf($production);

return $response;

This is useful because in a local environment, for instance, you might want to debug the errors instead of straight-up throwing exceptions!

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?