Exception Handling
- Login to post comments
ตอนนี้กำลังสงสัยว่า เราจะจัดการ Exception (Zend_Exception) อย่างไรดี ...
เช่น
// Some controller
<?php
class SomeController extends Zend_Controller_Front
{
... // some code
public function doSomethingAction()
{
if( empty($someRequiredValue) )
{
throw new Zend_Exception("The required value must not be empty!");
}
else
{
// continue working
...
}
}
... // some code
}
?>
// ใน bootstrap index.php
... // some code
$front = Zend_Controller_Front::getInstance();
$front->throwExceptions(true);
$front->setParam('noViewRenderer', true);
$front->setControllerDirectory(DOCUMENT_ROOT . "applications/controllers");
try
{
$front->dispatch();
}
catch(Exception $e)
{
echo $e->getMessage();
}
กำลังหา solution อยู่ว่า นอกจาก echo $e->getMessage(); แล้ว จะทำอะไรได้อีก ทำอย่างไร ... เช่น ถ้าต้องการแสดงหน้า default error ซักหน้า โดยมีหน้าตาเหมือนเว็บหลัก จะทำได้อย่างไร?
ใครพอมี solution มั้ยคับ??
ปล. ว่าจะไม่ redirect ด้วยน้ะ *_* อยากคง url เดิมมันไว้ หรือว่าต้อง redirect แต่แป่ะเพิ่ม param มาดีหว่า ...

โห เจ้าของเว็บมาถามเองแบบนี้ แล้วจะมีใครมาตอบให้หล่ะเนี่ย
ถ้าเป็นแบบไม่ใช่ zend ก็คงประมาณนี้ช่ายมะ (เอามาจาก rtd)
ขอบคุณ parnni มากครับ :D
แต่ประเด็นของเราก็คือ ใน bootstrap เราจะทำอะไรต่อได้บ้าง หลังจาก สั่ง $front->dispatch(); ไปแล้ว เช่น เราจะเซต ชื่อ controller ให้เป็นค่าอื่น เช่นเซต controller ให้เป็น SomeErrorController แล้วสั่ง dispatch อีกที เพื่อแสดงหน้า error ซักหน้า อะไรประมาณนี้
แต่ตัวอย่างที่ parnni ส่งมาให้ดู ก็เป็นตัวอย่างที่ดีน้ะคับ คนทำนี่ถือว่าโปรทีเดียว ... บางคนอาจจะมองข้าม หรืออาจจะไม่ได้มองข้าม แต่ขี้เกียจเช็คแบบนี้ไว้ก็ได้ (ผมก็เป็นในบางโอกาส และบางงาน) แต่ถ้าสำหรับโปรเจ็คที่ซีเรียสเรื่องการทำงาน เรื่องเงินๆ ทองๆ ซีเรียสเรื่องความสำคัญของข้อมูล ก็คงเลี่ยงไม่ได้ ที่ต้องทำไว้อย่างที่ parnni ส่งมาให้ดู :D
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
เซือในสิ่งที่เฮ็ด เฮ็ดในสิ่งที่เซือ...
ได้ solution มาแล้วอันนึง
แต่ก่อนทำยังงี้
try
{
$front->dispatch();
}
catch(Zend_Exception $e)
{
echo $e->getMessage());
}
ตอนนี้แก้เป็นยังงี้
try
{
$front->dispatch();
}
catch(Zend_Exception $e)
{
$front->throwExceptions(false);
$front->getRequest()->setParam('errMsg', $e->getMessage());
$front->dispatch();
}
แล้ว ZF จะส่งต่อไปให้ Zend_Front_Controller_Exception จัดการ และ Zend_Front_Controller_Exception ก็จะเรียกหา ErrorController::errorAction เราก็สร้าง ErrorController::errorAction เพื่อมา handler เราก็จะได้หน้า จัดการ error กลางๆ หน้าหนึ่ง ใน ErrorController::errorAction ผม implement ไว้ประมาณนี้
function errorAction()
{
$this->smarty->assign('errMsg', $this->_request->getParam('errMsg'));
$this->smarty->display($this->_controllerName . '/index.html');
}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
เซือในสิ่งที่เฮ็ด เฮ็ดในสิ่งที่เซือ...