简体   繁体   English

致命错误:找不到此类ID-API响应(PHP)

[英]Fatal error: Uncaught no such id - API response(PHP)

I am trying to get all infos from an API, where I dont know every single ID the API can get me. 我正在尝试从API获取所有信息,但我不知道API可以为我提供的每个ID。 So basically I am calling for 1 info after another while I increase the ID: 所以基本上我在增加ID的同时又要求1个信息:

<?php

$i = 0;
while ($i < 1000)
{
    if ($api->traits()->get($i) == "Uncaught no such id")
    {
        echo "do something";
        $i++;
    }
    else
    {
        echo "do something else";
        $i++;
    }
}

My error code: 我的错误代码:

Fatal error: Uncaught no such id (status: 404; url:....) 致命错误:找不到此类ID(状态:404; URL:....)

Is there a way that the program doesn't stop on a Fatal error? 有没有一种方法可以使程序不因致命错误而停止? Or that it reboot the script on fatal error with one higher ID? 还是在出现致命错误时以更高的ID重新启动脚本?

I believe you're seeing an Uncaught Exception . 我相信您会看到“未捕获的异常” See the catch block? catch块? That's what it means by "uncaught". 这就是“未捕获”的含义。

Try this: 尝试这个:

<?php
$i = 0;
while ($i < 1000)
{
    try
    {
        $trait = $api->traits()->get($i);
    }
    catch (Exception $ex)
    {
        echo "Error: " . $ex->getMessage();
        echo "(do something else)";

        $i++;
        continue;
    }


    echo "found trait " . $trait;
    $i++;
}

Also, this is probably a situation where you should use a for loop instead of a while loop. 同样,这可能是您应该使用for循环而不是while循环的情况。

<?php
for ($i = 0; $i < 1000; $i++)
{
    try
    {
        $trait = $api->traits()->get($i);
    }
    catch (Exception $ex)
    {
        echo "Error: " . $ex->getMessage();
        echo "(do something else)";

        continue;
    }


    echo "found trait " . $trait;
}

I should also add that Exception is the very base type or class of exception, and APIs and libraries will typically throw a more specific type of exception. 我还应该补充一点, ExceptionException的基本类型或类别,并且API和库通常会抛出更特定类型的异常。

catch (Exception $ex) { ... }

will catch any type of exception, but 将捕获任何类型的异常,但是

catch (HttpConnectionException $ex) { ... }

would only catch an Exception of type HttpConnectionException . 只会捕获类型为HttpConnectionException的Exception。 This allows you to handle specific types of errors differently. 这使您可以不同地处理特定类型的错误。 You can use get_class($ex) to see what exact type of Exception the API is throwing if you like. 如果愿意,可以使用get_class($ex)查看API get_class($ex)Exception的确切类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM