laravel12.laravel_100
最終投稿日:2026年3月15日
<?php
namespace App\Exceptions;
use Exception;
class MyException extends Exception {
// コンストラクタ
public function __construct($error = []) {
$this->code = $error['code'] ?? 0;
parent::__construct($error['message'] ?? '内部エラーが発生しました。');
}
}
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Configuration\Exceptions;
class ExceptionHandler {
public static function handle(Exceptions $exceptions) {
$exceptions->renderable(function (\Throwable $e, $request) {
// エラー種別判定
var_dump("OK");
});
}
}
use App\Exceptions\ExceptionHandler;
~ 省略 ~
->withExceptions(function (Exceptions $exceptions): void {
ExceptionHandler::handle($exceptions);
})->create();
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Configuration\Exceptions;
use App\Exceptions\MyException;
use Illuminate\Validation\ValidationException;
class ExceptionHandler {
public static function handle(Exceptions $exceptions) {
$exceptions->renderable(function (\Throwable $e, $request) {
$errors = [
'code' => $e->getCode(),
'path' => $e->getFile(),
'line' => $e->getLine(),
];
// バリデーションエラーは除外
if ($e instanceof ValidationException) {
return;
}
// エラー種別判定
if ($e instanceof MyException) {
$errors['title'] = 'MyException';
$errors['message'] = $e->getMessage();
} else {
$errors['title'] = $e->getMessage();
$errors['message'] = '内部エラーが発生しました。';
}
return response()->view("errors.500", ['errors'=> $errors]);
});
}
}
<!DOCTYPE HTML>
<HEAD>
<TITLE>SeverError</TITLE>
<link rel="stylesheet" href="{{ asset('css/base_css.css') }}" />
</HEAD>
<BODY>
{{ $errors['title'] }}
<BR />
{{ $errors['message'] }}
<BR />
{{ $errors['code'] }}
<BR />
{{ $errors['path'] }}
<BR />
{{ $errors['line'] }}
</BODY>
</HTML>
[500.blade.php]は、実はLaravelが500エラーを感知した際に自動的にレンダリングされるファイルでもあります。
今回はエラーハンドリングをしているため意識手にレンダリングしていますが、
例えば「~\errors\404.blade.php」なんてのもあります。
試しに作成して存在しないURLを叩いてみて下さい。
※ただしエラーハンドリングをしている場合は、今回の設定通り500エラーとなります。
エラークラスの基底となるクラスは『Throwable』となります。
この基底クラスから『Exception』『Error』クラスの2種類が枝分かれしています。
[PHP Ver.8]は両方のクラスを例外として[throw]しますが、[PHP Ver.7]は「Exception」のみを[throw]します。
先ほどのコード【$hoge=1/0;】のエラーは「Error」クラス起因ですので補足できないのです。
また「Throwable」であれば[PHP Ver.7]でも補足はできるのですが、このバージョンでのゼロ除算の扱いは「Warning」扱いのため【例外】ですらありません。