Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 我可以在ExtendeException类中放置什么?_Php_Error Handling_Try Catch - Fatal编程技术网

Php 我可以在ExtendeException类中放置什么?

Php 我可以在ExtendeException类中放置什么?,php,error-handling,try-catch,Php,Error Handling,Try Catch,我可以在扩展异常类中放置什么,以及如何使用它?如您所见,我在catch块中包含了错误 例如: class Manager { private $socket = null; private $config = array(); public function connect($host = null, $port = null) { if ($host == null || $port == null) { throw ne

我可以在
扩展异常
类中放置什么,以及如何使用它?如您所见,我在
catch
块中包含了错误

例如:

class Manager {

    private $socket = null;

    private $config = array();

    public function connect($host = null, $port = null) {

        if ($host == null || $port == null) {
            throw new PortHostNotGivenException('Host or Port is missing');
        }

        $this->socket = fsockopen($host,$post);

    }
}


class PortHostNotGivenException extends Exception {
    // What to put here??
 } 
测试:

$ast = new Manager();

    try {
      $ast->connect();
    } catch (PortHostNotGivenException $e) {
       // Log Error to File
       // Log Error to Linux Console
       echo $e . '/r/n';
       exit();
    }

您可以捕获多个不同的异常并以不同的方式处理它们,例如

try {
    $this->db->save();
} catch (ConnectionException $e) {
    if ($this->db->reconnect()) {
        // try again
    } else {
        throw new CannotReconnectException();
    }
} catch (ValidationException $e) {
    // display validation error messages
} catch (Exception $e) {
    // save failed with a general or unexpected error
}
您还可以静默处理预期错误,同时不干扰意外错误:

try {
  ...
} catch (VendorApiException $e) {
    return false;
}
在上面的示例中,如果抛出一个
VendorApiException
,代码将返回false。如果抛出任何其他异常,则此
catch
块将不会捕获它,而是冒泡出现。如果没有更高的try/catch块,它将由进程处理

用户定义的异常主体 //在这里放什么


任何东西或什么都没有-如果你没有理由覆盖任何一个-不要在里面放任何东西。通常,您可以定义
code
message
,如果传递的
$message
不是字符串,则可能会覆盖构造函数。

您不需要在其中放置任何内容。扩展和异常的目的主要是“过滤”正在捕获的异常


例如,您有一个CustomConfigNotFoundException和一个DatabaseException,其中您可以说meh我不需要自定义配置,因为我可以暂时使用默认配置,但如果没有数据库,您就完了。。。因此,您可以使用catch(CustomConfigNotFoundException e)加载默认配置,并让DatabaseException停止您使用的任何程序/脚本/页面异常。

我想我将在每个
catch
中重复相同的代码,例如:将错误记录到文件,将错误记录到Linux控制台,等等。干法的最佳方法是什么。@我会回来的,如果你所做的只是记录异常,不要捕捉它们。相反,让它们冒泡到您的顶级异常处理程序(您可以使用
set\u exception\u handler
)并将其记录在那里。依我看,例外情况只有在可恢复的情况下才能被捕获。否则,您的应用程序应该正常停止(带有一个漂亮的警告页面),否则您将面临更大的风险issues@ColinMorelliPHP脚本将在Linux上的后台进程中运行-因此我正在寻找处理此类错误处理的好解决方案。@我将再次返回,正如AD7和我提到的,除非可以恢复,否则只需使用全局异常处理程序。@I'll-Back长期运行的进程和php不能很好地结合在一起。编写代码以处理您知道它可以处理的内容,并使用运行/管理守护进程,例如,以便在进程死亡时重新启动进程。如果您使用的是db,请预测并说明连接超时=)