エラーハンドリング¶
CodeIgniter は Exception によってエラーレポーティングを行います。SPL 標準の例外 といくつかのフレームワーク独自の例外があります。環境設定によりますが、例外が投げられたときのデフォルトの挙動ではエラーの詳細を表示します。production
環境では表示しません。In this case, a more generic message is displayed to
keep the best user experience for your users.
例外の利用¶
This section is a quick overview for newer programmers, or for developers who are not experienced with using exceptions.
例外とはシンプルなイベントで、exception が「投げられた」ときに発生します。次のものは現在のスクリプト処理の流れを停止させ、エラーハンドラに処理を渡し、適切なエラーページを表示します:
throw new \Exception("何かメッセージをここに書く");
If you are calling a method that might throw an exception, you can catch that exception using a try/catch
block:
try {
$user = $userModel->find($id);
}
catch (\Exception $e)
{
die($e->getMessage());
}
$userModel
が例外を投げたなら、それをキャッチして catch ブロックの中を実行します。この例では、UserModel
で定義したエラーメッセージを表示して、スクリプトは死にます。
またこの例では、あらゆる型の例外をキャッチします。もし特定の型の例外だけを監視したいなら、例えば UnknownFileException なら、catch のパラメータに指定します。このクラスまたは小クラス以外の例外はキャッチされず、エラーハンドラにスルーパスされます:
catch (\CodeIgniter\UnknownFileException $e)
{
// ここで何か行う……
}
This can be handy for handling the error yourself, or for performing cleanup before the script ends. もしこの特定のエラーを標準的なエラーとしてエラーハンドラに処理させたいなら、新しい例外を生成して投げます[訳注: このコード例ではスタックトレースが切れてしまうため、第3引数に $e を渡すことが望ましいです]:
catch (\CodeIgniter\UnknownFileException $e)
{
// ここで何かする……
throw new \RuntimeException($e->getMessage(), $e->getCode(), $e);
}
設定¶
デフォルトでは、CodeIgniter は development
環境と testing
環境ではすべてのエラーを表示します。production
環境ではすべて表示しません。この挙動は変更することができます。index.php
ファイルの先頭のほうにある環境設定の箇所がそうです。
重要
エラーレポーティングの無効化はログ出力を 止 め ま せ ん 。
Logging Exceptions¶
By default, all Exceptions other than 404 - Page Not Found exceptions are logged. This can be turned on and off
by setting the $log value of Config\Exceptions
:
class Exceptions
{
public $log = true;
}
To ignore logging on other status codes, you can set the status code to ignore in the same file:
class Exceptions
{
public $ignoredCodes = [ 404 ];
}
注釈
It is possible that logging still will not happen for exceptions if your current Log settings are not setup to log critical errors, which all exceptions are logged as.
独自の例外¶
つぎの独自の例外が使用可能です:
PageNotFoundException¶
404 Page Not Found エラーのシグナルとして使います。When thrown, the system will show the view found at
/app/views/errors/html/error_404.php
. エラーの view ファイルはすべてサイトに合わせてカスタマイズすべきです。
もし、Config/Routes.php
で 404 オーバーライドを指定しているなら、標準の 404 ページの代わりにそれが呼び出されます:
if (!$page = $pageModel->find($id))
{
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
例外にメッセージを渡せば、404 ページのデフォルトメッセージの箇所にそれが表示されます。
ConfigException¶
この例外は設定クラスの値が不正な場合に使用すべきものです。設定クラスの型が違う場合、など:
throw new \CodeIgniter\Exceptions\ConfigException();
This provides an HTTP status code of 500 and an exit code of 3.
DatabaseException¶
データベースエラー発生時にこの例外は投げられます。DB コネクションを作れなかったときや、一時的に失ってしまったときなどです:
throw new \CodeIgniter\Database\Exceptions\DatabaseException();
This provides an HTTP status code of 500 and an exit code of 8.