如何使用Laravel在Controller中捕获500错误

时间:2018-10-25 14:44:46

标签: php laravel error-handling guzzle guzzle6

我需要连接到API,所以我编写了一个函数:

try {
    $res4 = $client3->post('https://api.example.co.uk/Book', [
        'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ajhsdbjhasdbasdbasd',
        ],
        'json' => [
            'custFirstName' => $FirstName,
            'custLastName' => $Surname,
            'custPhone' => $Mobile,
            'custEmail' => $Email,
        ]
    ]);
} catch (GuzzleHttp\Exception\ClientException $e) {
    $response = $e->getResponse();
    $result = json_decode($response->getBody()->getContents());
    $item->update(['status' => 'Problems at step3']);
    Mail::raw('Problem at STEP 3', function ($message) use ($serial) {
        $message->from('asd.asd@gmail.com', 'asd.asd@gmail.com');
        $message->subject('We got a problem etc.');
        $message->to('john.smith@gmail.com');
    });
}

如您所见,我需要调用API,但是在API中断的情况下,我会编写catch函数。

但是现在当API关闭并且API返回“ 500 Internal Error”时,此函数就崩溃了...

我的问题是为什么不抓捕它?

如何处理错误-当API中断或请求错误时...为什么catch {}不起作用?

更新:这是我的laravel.log

[2018-10-25 14:51:04] local.ERROR: GuzzleHttp\Exception\ServerException: Server error: `POST https://api.example.co.uk/Book` resulted in a `500 Internal Server Error` response:
{"message":"An error has occured. Please contact support."}
 in /home/public_html/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:107
Stack trace:
#0 /home/public_html/vendor/guzzlehttp/guzzle/src/Middleware.php(65): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response))
#1 /home/public_html/vendor/guzzlehttp/promises/src/Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response))

3 个答案:

答案 0 :(得分:1)

问题是这里的名称空间,而不是:

} catch (GuzzleHttp\Exception\ClientException $e) {

您应该使用:

} catch (\GuzzleHttp\Exception\ClientException $e) {

否则,PHP假定该类在当前的名称空间中,因此实际上,当您使用GuzzleHttp\Exception\ClientException时,实际上您可能使用了App\Http\Controllers\GuzzleHttp\Exception\ClientException,并且这种异常显然不会被Guzzle抛出。

答案 1 :(得分:0)

引发的异常是ServerException实例,并且catch块尝试捕获ClientException。

} catch (GuzzleHttp\Exception\ServerException $e) {

答案 2 :(得分:0)

  

在您的app / exceptions / handler.php文件中,更新这种渲染方法。

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception) {
    if ($exception instanceof \GuzzleHttp\Exception\ClientException) {
        return your_response();
    }
    return parent::render($request, $exception);
}
  

这种方法对我有用。