2016-12-05 159 views
1

我有這個函數可以得到URLS的狀態碼,如果提供了一個虛假的URL,它只是通過例外說「假url」。我想處理這個異常,並像404一樣對待,該網站已關閉。laravel:異常處理

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

     return $response->getStatusCode(); 
    } 

我試過這段代碼,但沒有幫助。我需要你的幫助來弄明白嗎?

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;  
    } 

} 

回答

1

你嘗試過這件事情與改變程序代碼來渲染方法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); 
    } 
} 

變化404pageURL500pageURL根據您的需要。不過,我沒有測試這個代碼,但它應該適合你。