2011-07-22 14 views

cevap

33

Tabii İçin

. Sadece farkında olmak için hata işleme kodunuza bağlı olacak ve dizi özelliğini uygun şekilde kullanacaksınız. Sen mesela, istediğiniz herhangi bir parametre almaz için özel istisna sınıfının yapıcısı tanımlayın ve sonra sadece yapıcı tanımının içinden temel sınıfın kurucusunu çağırmak için emin olabilir:

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; } 
} 

Ardından, çağıran kod ... Evet, yapabilirsiniz

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

+4

Hey adam 'Exception'ı genişletmeyi unuttun ':) –

2

:

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

istisna sınıfı uzatılması için php dokümanlar göz at. Exception class'u genişletmeniz ve istediğiniz şeyi yapmak için bir __construct() yöntemi oluşturmanız gerekecektir.

8

Sanırım cevapla biraz geciktim ama çözümümü de paylaşmak istedim. Bu seyir için daha fazla kişi muhtemelen Orada İstisna uzatmak istemiyorsanız

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); 
    } 
} 
+3

json_decode'a ikinci bir parametre olarak true ekleyerek bir dizi döndürülürse, bir nesne döndürülürse –

0

, bir dizeye dizinizi kodlamak :) şunlardır:

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()); 
} 

da kullanabilirsiniz json_encode/json_decode Eğer tercih edersen.

İlgili konular