abraham foto
abraham foto

Reputation: 457

laravel: exception handling

I have this function which is able to get status code of URLS, if a fake URL is provided, it simply through exceptions that says "fake url". i want to handle that exception and treat it like 404, the site is down.

private function getStatusCode($url)
    {
        $response = $this->client->get($url, [
            'http_errors' => false
        ]);

        return $response->getStatusCode();
    }

i tried this code but doesnt help. i need your help to figure it out?

private function getStatusCode($url)
  {
    try{
     $response = $this->client->get($url, [
      'http_errors' => false
      ]);

     return $response->getStatusCode();
   }     
  //catch specific exception....
   catch(QueryException $e)
   {
      //...and do whatever you want
    return $response;    
  }

}

Upvotes: 1

Views: 644

Answers (1)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

Have you tried this thing with change code to render method in app/Exceptions/Handler.php?

public function render($request, Exception $e)
{
  if($this->isHttpException($e))
  {
    switch ($e->getStatusCode()) {
      // 404 not found
      case '404':
      return redirect()->guest('404pageURL');
      break;

      // internal error
      case '500':
      return redirect()->guest('500pageURL');
      break;

      default:
          return $this->renderHttpException($e);
      break;
    }
  }
  else
  {
    return parent::render($request, $e);
  }
}

Change 404pageURL and 500pageURL based on your requirement. However I'm not tested this code but it should work for you.

Upvotes: 1

Related Questions