我正在嘗試捕獲 HTTP 客戶端操作期間發生的錯誤。如果啟用了除錯,APP_DEBUG=true那么我會得到一個錯誤跟蹤,如果它關閉,那么它會出現 json response "message": "Server Error"。但我需要捕捉例外,它不起作用。試過了 catch (\Illuminate\Http\Client\ConnectionException $e),但是沒有用。我究竟做錯了什么?
public function ExampleMethod()
{
try {
$response =
Http::withBasicAuth(env('REMOTE_LOGIN'), env('REMOTE_PASSWORD'))
->accept('application/json')
->retry(3, 2000)->timeout(12)
->withBody("dummy body content", "application/json")
->post($host . $url);
if ($response->ok()) {
//Do something
}
} catch (Exception $e) {
dd("CATCH IT");
}
}
檔案中有一個示例,域不存在,例外處理程式應該在某處作業,但它不起作用
public function catchExceptins()
{
try {
$url = "domain-is-not-exist.com";
$response = Http::get($url);
if ($response->ok()) {
dd("200 OK");
}
//
if($response->failed()){
dd("FAILED");
}
//Below are the handlers that should work,
//but they do not respond when there is no domain
//or for example if the server response is 505
if($response->serverError()) {
dd("FAILED");
}
if($response->clientError()) {
dd("FAILED");
}
$response->throw(function($response, $e){
dd("FAILED");
})->json();
} catch (Exception $e) {
dd($e);
}
}
uj5u.com熱心網友回復:
Laravel 的 HTTP 客戶端包裝器提供了一種處理錯誤的機制,其中包含許多有用的方法。
public function ExampleMethod()
{
try{
$response = Http::withBasicAuth(env('REMOTE_LOGIN'), env('REMOTE_PASSWORD'))
->accept('application/json')
->retry(3, 2000)->timeout(12)
->withBody("dummy body content", "application/json")
->post($host . $url);
//Check for any error 400 or 500 level status code
if($response->failed()){
// process the failure
}
//Check if response has error with 500 level status code
if($response->serverError()) {
//process on server error
}
//Check if response has error with 400 level status code
if($response->clientError()) {
//process on client error
}
// It also allows to throw exceptions on the $response
//If there's no error then the chain will continue and json() will be invoked
$response->throw(function($response, $e){
//do your thing
})->json();
}
catch(\Exception $e) {
//$e->getMessage() - will output "cURL error 6: Could not resolve host" in case of invalid domain
}
}
Laravel 檔案 - Http 客戶端 - 例外處理
uj5u.com熱心網友回復:
當您設定 APP_DEBUG=false 時,它??只是向最終用戶顯示一個通用錯誤以確保安全,但應該在 Laravel 日志中為您提供詳細的錯誤。'All' APP_DEBUG=true 的作用是通過在前端顯示日志來簡化開發程序。
你的 Laravel 日志應該在“/storage/logs”里面。
https://laravel.com/docs/9.x/configuration#debug-mode
https://laravel.com/docs/9.x/errors#configuration
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489153.html
上一篇:只知道名稱就拋出例外?
下一篇:關于例外宣告的澄清
