1

我目前正在编写用于与返回status字段的 WebService 交互的代码代码,该字段是一个描述操作失败的数字。有二十个status值:10, 11, 12, 20...37. 您将如何根据代码正确抛出异常?

创建二十个或更多 CodeXXGatewayExceptionXX代码在哪里)似乎需要做很多工作,而且肯定不是一个简洁的解决方案:

class Code10GatewayException
{
    public function __construct()
    {
        parent::__construct('Generic Error.', 10);
    }
}

class Code11GatewayException
{
    public function __construct()
    {
        parent::__construct('Invalid charset.', 11);
    }
}

// Throw the exception
$class = "My\Exception\Client$statusException";
throw new $class;

带有的异常工厂怎么样$reasonMap?人们(通常)如何处理大型项目中的大量异常?

class GatewayException extends \RuntimeException
{
    public function __construct($code, $reason)
    {
        parent::__construct($reason, $code);
    }
}

class ExceptionFactory
{
    public static $reasonMap = array(
        '10' => 'Generic error',
        '11' => 'Invalid charset',
        // ...
    );
    public static function fromStatus($status)
    {
        return new GatewayException($status, self::$reasonMap[$status] . '.');
    }
}

// Throw the exception
throw new ExceptionFactory::fromStatus($status);
4

1 回答 1

-2
<?php
class GatewayException extends Exception
{
    protected $reasonMap = array(
        10 => 'Generic error'
    );

    public function __construct($code)
    {
        $this->code = $code;
        $this->message = $this->reasonMap[$code];
    }
}

...

throw new GatewayException(10);
于 2013-07-16T10:27:18.607 回答