2012-01-11 11 views
7

所以我有獲取一個文件如何拋出一個陣列異常在PHP

$error_message = "Error received for " . $service . ": " . $_r['status'] . "\n" . "Message received: " . $_r['errors']; 
throw new My_Exception($error_message); 

,並在另一個文件中拋出的錯誤消息我

try { 
    //blah blah 
} catch(My_Exception $e) { 
    var_export($e->getMessage()); 
} 

的問題,然而,$ _r ['errors']是一個ARRAY,它得到$ e-> getMessage()只是將它打印爲「Array」。我如何修改這段代碼來訪問數組?

回答

8

一個複雜的數據結構類似於數組轉換成字符串(如錯誤消息),您可以使用print_r­Docs並設置它的第二個參數TRUE

... ": " . print_r($_r['status'], TRUE) . "\n" ... 
14

的問題是,你試圖將數組與字符串合併。它會一直這樣結束。

也許你應該傳遞一個異常數組,所以你可以在以後使用它?

<?php 
class myException extends Exception { 

    private $params; 

    public function setParams(array $params) { 
     $this->params = $params; 
    } 

    public function getParams() { 
     return $this->params; 
    } 
} 

// later it can be used like this: 
try { 
    $exception = new myException('Error!'); 
    $exception->setParams(array('status' => 1, 'errors' => array()); 

    throw $exception; 
} 
catch (myException $e) { 
    // ... 
} 
?> 
+0

這是錯誤的形式,因爲它打破了異常的基本界面。如果您需要傳遞一些值 - 只需添加一個收集和存儲它們的方法即可。 – Xeoncross 2012-01-11 18:51:03

+0

@Xeoncross你說得對。我會解決這個問題。 – radmen 2012-01-11 18:53:23

+1

+1完美。現在,該對象正在獲得,而不是失去功能。 – Xeoncross 2012-01-11 19:01:28

0

所以你的示例代碼是有點不好,但假設

$_r['errors'] = array(
    'Message 1', 
    'Message 2', 
    'Message 3', 
    'Message 4', 
    'Message 5', 
); 

然後

$error_message = "Error received for " . $service . ": \n" . impolode("\n", $_r['errors']) . "\n" . "Message received: " . $_r['errors']; 
throw new My_Exception($error_message); 

的關鍵是把你的錯誤信息陣列,並與新行一起連接起來將所有(或不管)

但我有點同意您可能會使用異常fram ework錯誤。你能發表你想要做的事嗎?

一般的經驗法則是,你爲每個獨特的事件拋出異常。你不會收集一堆錯誤消息,然後立即將它們全部扔掉。