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

sshateri's avatar

Catch Laravel Http errors

I'm using Laravel Http to call an API and get a list of the latest transactions. I can check the errors like failed authentication or such using failed(); or successful(); methods but errors like failed to connect to the API like the cURL error 6 cant be handled that way apparently and it throws the error page. I would like to be able to handle errors like API URL couldn't be resolved or such errors that cURL throws in a simple manner just to know there has been an error and show a custom message instead.

public function index()
    {
        $status = "100";
        $page = "0";
        $page_size = "10";
        $idpay = Http::withHeaders([
            'Content-Type' => 'application/json',
            'X-API-KEY' => 'xxxxxx',
            'X-SANDBOX' => '1'
        ])->post("https://api.idpay.ir/v1.1/payment/transactions?page=$page&page_size=$page_size");


        if ($idpay->successful())
        {
            return view('supporters')->with('idpay', $idpay->json())->with('idpayFailed', false);
        }
        elseif ($idpay->failed()){
            return view('supporters')->with('idpayFailed', true);
        }
    }
0 likes
5 replies
sshateri's avatar

I saw that before asking the community but didn't get how to implement it. I used the example but it didn't work.

sshateri's avatar

so I refactored my code as follows but still didn't work. I'm still getting the original laravel error page upon failing to resolve the API URL.

try{
            $status = "100";
            $page = "0";
            $page_size = "10";
            $idpay = Http::withHeaders([
                'Content-Type' => 'application/json',
                'X-API-KEY' => 'xxxx',
                'X-SANDBOX' => '1'
            ])->post("https://api.idpay.ir/v1.1/payment/transactions?page=$page&page_size=$page_size")->throw();
        }
        catch (RequestException $e){
            return view('supporters')->with('idpayFailed', true)->with('idpayError', $e->response->json());
        }
sshateri's avatar

but then i did this and it works.

try{
            $status = "100";
            $page = "0";
            $page_size = "10";
            $idpay = Http::withHeaders([
                'Content-Type' => 'application/json',
                'X-API-KEY' => 'xxxxx',
                'X-SANDBOX' => '1'
            ])->post("https://api.idpay.ir/v1.1/payment/transactions?page=$page&page_size=$page_size")->throw();
        }
        catch (Throwable $e){
            return view('supporters')->with('idpayFailed', true)->with('idpayError', $e->getMessage());
        }

i really don't understand why this is working but not the other one that i posted above.

Please or to participate in this conversation.