如果发生多个错误,如何只显示一个错误?

So, I have this api on my website that will sometimes get HTTP errors due to the the site I'm grabbing data from having some downtime. I was wondering how I could only display only one error if multiple errors occur using a custom error handler?

Here's my current code:

function Error($errno, $errstr, $errfile, $errline) {
  echo "ERROR";
  error_log($errstr . " - on line " . $errline);
}
set_error_handler("Error");

I found a solution. die() prevents the function from being called again. But this also means if there's another error then it wouldn't be logged since the function would only be called once.

function Error($errno, $errstr, $errfile, $errline) {
    echo "ERROR";
    error_log($errstr . " - on line " . $errline);
    die();
}
set_error_handler("Error");

You could store all your errors inside an array and then just display the first error in the array.

Given you have no control over it the best way is not really going to be clean - i.e. there are likely better ways with cleaner code overall.

I don't know much about the rest of your code, but you need to wrap this entire thing in a check to see if there is an error. I don't know where the vars etc come from, but presume PHP standard, e.g.

if (!empty($errno)) {
    function Error($errno, $errstr, $errfile, $errline) {
        error_log($errstr . " - on line " . $errline);
    }
    set_error_handler("Error");

    if (empty($errorWasDisplayed)) {
        $errorWasDisplayed = true;
        echo "whatever your error message is";
    }
}

It'll always be the first error, but if you need a specific one then you just simply need to adjust the condition to factor that in.

You can return a value from your function if needed to show in the error message.