簡體   English   中英

你能在 php 中拋出一個數組而不是字符串作為異常嗎?

[英]Can you throw an array instead of a string as an exception in php?

我想在 php 中將數組作為異常拋出,而不是字符串。 如果您定義自己的擴展異常 class 的 class,是否可以這樣做?

例如throw new CustomException('string', $options = array('params'));

當然。 這將取決於您的錯誤處理代碼,並適當地使用數組屬性。 您可以定義自定義異常類的構造函數以獲取所需的任何參數,然后確保從構造函數定義中調用基類的構造函數,例如:

class CustomException extends \Exception
{

    private $_options;

    public function __construct($message, 
                                $code = 0, 
                                Exception $previous = null, 
                                $options = array('params')) 
    {
        parent::__construct($message, $code, $previous);

        $this->_options = $options; 
    }

    public function GetOptions() { return $this->_options; }
}

然后,在您的調用代碼中...

try 
{
   // some code that throws new CustomException($msg, $code, $previousException, $optionsArray)
}
catch (CustomException $ex)
{
   $options = $ex->GetOptions();
   // do something with $options[]...
}

查看 php 文檔以擴展異常 class:

http://php.net/manual/en/language.exceptions.extending.php

我想我的答案有點太晚了,但我也想分享我的解決方案。 可能有更多的人在尋找這個:)

class JsonEncodedException extends \Exception
{
    /**
     * Json encodes the message and calls the parent constructor.
     *
     * @param null           $message
     * @param int            $code
     * @param Exception|null $previous
     */
    public function __construct($message = null, $code = 0, Exception $previous = null)
    {
        parent::__construct(json_encode($message), $code, $previous);
    }

    /**
     * Returns the json decoded message.
     *
     * @param bool $assoc
     *
     * @return mixed
     */
    public function getDecodedMessage($assoc = false)
    {
        return json_decode($this->getMessage(), $assoc);
    }
}

如果不想擴展 Exception,可以將數組編碼為字符串:

try {
  throw new Exception(serialize(['msg'=>"Booped up with %d.",'num'=>123]));
} catch (Exception $e) {
  $data = unserialize($e->getMessage());
  if (is_array($data))
    printf($data['msg'],$data['num']);
  else
    print($e->getMessage());
}

如果您願意,也可以使用json_encode / json_decode

是的你可以。 您需要擴展異常 class並創建一個 __construct() 方法來執行您想要的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM