2016-05-31 66 views
3

我不明白如何用PHP正確創建並返回有用的錯誤信息到Web。用PHP返回有用的錯誤信息

我有一個類

class Foo { 
    const OK_IT_WORKED = 0; 
    const ERR_IT_FAILED = 1; 
    const ERR_IT_TIMED_OUT = 3; 

    public function fooItUp(){ 
     if(itFooed) 
      return OK_IT_WORKED; 
     elseif(itFooedUp) 
      return ERR_IT_FAILED; 
     elseif(itFooedOut) 
      return ERR_IT_TIMED_OUT; 
    } 
} 

和使用這個類做一些有用的另一個類,然後將結果返回給用戶。我只是想知道我把所有的錯誤消息的字符串值。

class Bar { 
    public function doFooeyThings(stuff){ 
     $res = $myFoo->fooItUp(); 
     // now i need to tell the user what happened, but they don't understand error codes 
     if($res === Foo::OK_IT_WORKED) 
      return 'string result here? seems wrong'; 
     elseif ($res === Foo::ERR_IT_FAILED) 
      return Foo::ERR_IT_FAILED_STRING; // seems redundant? 
     elseif($res === Foo:ERR_IT_TIMED_OUT) 
      return $res; // return number and have an "enum" in the client (js) ? 
    } 

} 

回答

2

您應該儘可能避免返回錯誤狀態。改用異常。如果你從未使用異常,然後才能閱讀它們here

在你的例子中有多種方法可以使用異常。您可以爲每個錯誤或每類錯誤創建自定義例外。有關自定義例外here的更多信息,或者您可以創建類的默認Exception實例,將錯誤消息作爲字符串提供給它。

下面的代碼如下第二種方法:

class Foo { 
    const OK_IT_WORKED = 0; 
    const ERR_IT_FAILED = 1; 
    const ERR_IT_TIMED_OUT = 3; 

    public function fooItUp(){ 
     if(itFooed) 
      return OK_IT_WORKED; 
     else if(itFooedUp) 
      throw new Exception("It failed") 
     else if(itFooedOut) 
      throw new Exception("Request timed out"); 
    } 
} 

我相信你能想到比我以前的那些多一些優雅的消息。無論如何,你可以再繼續使用try/catch塊處理呼叫者方法這些例外:

class Bar { 
    public function doFooeyThings(stuff){ 
     try 
     { 
      $res = myFoo->fooItUp(); 
     } 
     catch(Exception $e) 
     { 
      //do something with the error message 
     } 

    } 

} 

無論異常是從fooItUp拋出將被「捕獲」由catch塊,並通過代碼來處理。

你也應該考慮

兩件事情:

  • 最好不要顯示你的用戶,因爲這些信息可以通過用戶與惡意使用

  • 理想情況下,你應該有關於錯誤的詳細信息某種全局異常處理

1

一種解決方案是將異常與set_exception_handler()

<?php 

set_exception_handler(function($e) { 
    echo "Error encountered: {$e->getMessage()}"; 
}); 

class ErrorMessageTest 
{ 
    public function isOk() 
    { 
     echo "This works okay. "; 
    } 

    public function isNotOkay() 
    { 
     echo "This will not work. "; 
     throw new RuntimeException("Violets are red, roses are blue!! Wha!?!?"); 
    } 
} 

$test = new ErrorMessageTest(); 

$test->isOk(); 
$test->isNotOkay(); 

set_exception_handler()方法需要一個可接受的方法來接受異常作爲其參數。這讓我們提供自己的邏輯來處理拋出的異常,如果它不在try/catch中。

Live Demo

參見:set_exception_handler() documentation