我试图捕捉HTTP客户端操作期间发生的错误。如果启用了调试,APP_DEBUG=true,那么我会得到一个错误跟踪,如果它是关闭的,那么它就会出现json "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);
}
}发布于 2022-06-06 22:02:57
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
}
}发布于 2022-06-03 22:17:13
当您设置APP_DEBUG=false时,它只会向最终用户显示一个一般性错误,以保证安全性,但是应该会在Laravel日志中给出详细的错误。APP_DEBUG=true所做的一切,就是通过在前端显示日志来简化开发过程。
您的Laravel日志应该在“/存储/日志”中。
https://stackoverflow.com/questions/72494753
复制相似问题