この便利な小さなクラスを考えてみましょう。
class FunkyFile {
private $path;
private $contents = null;
public function __construct($path) {
$this->setPath($path);
}
private function setPath($path) {
if( !is_file($path) || !is_readable($path) )
throw new \InvalidArgumentException("Hm, that's not a valid file!");
$this->path = realpath($path);
return $this;
}
public function getContents() {
if( is_null($this->contents) ) {
$this->contents = @file_get_contents( $this->path );
if($this->contents === false)
throw new \Exception("Hm, I can't read the file, for some reason!");
}
return $this->contents;
}
}
それは例外の完全に素晴らしい使用です。FunkyFile's
視点から見ると、パスが無効またはfile_get_contents
失敗した場合に状況を改善するためにできることはまったくありません。本当に例外的な状況;)
しかし、あなたのコードのどこかに間違ったファイルパスを見つけたことをユーザーが知る価値はありますか?例えば:
class Welcome extends Controller {
public function index() {
/**
* Ah, let's show user this file she asked for
*/
try {
$file = new File("HelloWorld.txt");
$contents = $file->getContents();
echo $contents;
} catch(\Exception $e) {
log($e->getMessage());
echo "Sorry, I'm having a bad day!";
}
}
}
あなたが悪い日を過ごしていることを人々に伝える以外に、あなたの選択肢は次のとおりです。
後退する
情報を取得する別の方法はありますか?上記の簡単な例では、可能性は低いようですが、マスター/スレーブデータベーススキーマを検討してください。マスターは応答に失敗した可能性がありますが、多分、たぶん、スレーブがまだそこにいます(またはその逆)。
ユーザーのせいですか?
ユーザーは誤った入力を送信しましたか?まあ、彼女にそれを教えてください。エラーメッセージを鳴らすか、適切なパスを入力できるように、フォームにエラーメッセージを添えることができます。
それはあなたのせいですか?
そして、あなたによって、私はユーザーではないものを意味するので、それはあなたが間違ったファイルパスを入力することから、あなたのサーバーでおかしくなる何かまでの範囲です。厳密に言えば、503 HTTPエラーの時が来たので、サービスも利用できません。CIにはshow_404()
機能があり、簡単にビルドできますshow_503()
。
アドバイスの言葉、あなたは不正な例外を考慮する必要があります。CodeIgniterは厄介なコードであり、例外がいつポップアップするかはわかりません。同様に、あなたはあなた自身の例外を忘れるかもしれません、そして最も安全なオプションはキャッチオール例外ハンドラを実装することです。PHPでは、set_exception_handlerを使用してこれを実行できます。
function FunkyExceptionHandler($exception) {
if(ENVIRONMENT == "production") {
log($e->getMessage());
show_503();
} else {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
}
}
set_exception_handler("FunkyExceptionHandler");
また、set_error_handlerを使用して、不正なエラーを処理することもできます。例外と同じハンドラーを記述するか、すべてのエラーを変換しErrorException
て例外ハンドラーに処理させることができます。
function FunkyErrorHandler($errno, $errstr, $errfile, $errline) {
// will be caught by FunkyExceptionHandler if not handled
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("FunkyErrorHandler");