2011-03-22 62 views
0

我有這樣一類的最佳方式:方法retuns錯誤代碼或什麼是做

class myclass { 
    public function save($params){ 
     // some operations 
     // posible error 
     return false; 
     // some more code 
     // posible error 
     return false; 
     // more code 
     // if everything is ok 
     return true; 
    } 
} 

但什麼是顯示錯誤的最好辦法,一個想法是讓類返回的數字像例如:

public function save($params) { 
    // some operations 
    // some error with the db 
    return 1; 
    // more code 
    // some error with a table 
    retunr 2; 
    // more code 
    // if everything is ok 
    return 0; 
} 

並且當人調用此函數,進行切換以顯示該錯誤:

$obj = new myclass(); 
$err = $obj->save($params); 
switch($err) { 
    case 1: echo 'error with the db'; break; 
    case 2: echo 'error with some table'; break; 
    default: echo 'object saved!'; 
} 

這是寫這個的最好方法嗎?或者有另一種方式?

回答

2

許多編程語言爲您提供拋出和捕捉異常的選項。在可用的情況下,這通常是更好的錯誤處理模型。

public function save($params) throws SomeException { 
    // some operations 
    if (posible error) 
     throw new SomeException("reason"); 
} 


// client code 
try { 
    save(params); 
} catch (SomeException e) { 
    // log, recover, abort, ... 
} 

Exceptions的另一個優點是它們(至少在某些語言中)可以讓您訪問堆棧跟蹤以及消息。

+0

許多語言也有一組豐富的錯誤代碼,正等待使用(例如Win32平臺上的HRESULT)。我不打算採取一個與另一個的立場,但他們都解決了這個問題。 :) – paulcam 2011-03-22 09:36:48

+0

是的,我會在課堂內放置一個異常,而當我打電話給那個班級時,我認爲這樣更乾淨。 – armandfp 2011-03-22 12:06:37

0

錯誤代碼和異常是一個非常有趣的參數,我個人更喜歡異常,但錯誤代碼有它們的位置。 have a look at this link

+0

謝謝,是一篇很好的文章:) – armandfp 2011-03-22 12:06:52

+0

就錯誤代碼與異常而言,這篇文章可以總結爲「錯誤代碼*有時候*會讓你編寫更簡潔的代碼」,並且不會有太大的回退聲稱。 – dimo414 2014-08-22 04:21:18