อย่างไรก็ตาม มีบางกรณีที่ทำให้ exception ไม่ถูก handle ในส่วนของ catch และถูก throw ออกไปโดยไม่มีการ handle ใดๆ
ผมจะใช้โค้ดตัวอย่างเพื่อแสดงว่า โค้ดส่วนใดที่คุณต้องระวังเป็นพิเศษ
โค้ดทั้งสองตัวอย่างเป็น Laravel commands ที่สามารถเรียกใช้งาน โดยรันคำสั่งใน console ดังนี้
php artisan test-exceptionตัวอย่างที่ 1 กำหนด Exception Namespace ไม่ถูกต้อง
<?php
namespace App\Ship\Commands;
use App\Ship\Parents\Commands\ConsoleCommand;
class TestCommand extends ConsoleCommand
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'test-exception';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Test exception';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
try {
abc;
} catch (Exception $ex) {
dump('There is error.');
}
}
}
ผลลัพธ์การรันจะเป็นดังภาพตัวอย่างที่ 2 กำหนด Exception Namespace ถูกต้อง
<?php
namespace App\Ship\Commands;
use App\Ship\Parents\Commands\ConsoleCommand;
use Exception;
class TestCommand extends ConsoleCommand
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'test-exception';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Test exception';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
try {
abc;
} catch (Exception $ex) {
dump('There is error.');
}
}
}
No comments:
Post a Comment