:::
8-4 異常處理
- 遇到錯誤就直接die(),實際上並不太好。
- 一來有些控制器可能還沒執行完或者沒有正常關閉。
- 二來畫面實在很醜。
- 此時,我們可以利用PHP內建的異常處理機制。
一、拋出異常
- 把die()直接換成,如:throw new Exception()
if (empty($name)) { throw new Exception("姓名為必填!"); } -
可用 Ctrl + H 來全部取代
-
有些在 or 後面的要改成:
if (!$db->query($sql)) { throw new Exception($db->error); }
二、接收異常,並處理之
- 凡是有可能出現異常情形的,一般用try{} catch{}來執行並接收異常,例如:我們 try 整個 switch,只要其中有任何異常,都可以用 catch 去捕捉到!
try { switch ($op) { case 'login': login(); header("location:{$_SERVER['PHP_SELF']}"); exit; case "logout": logout(); header("location:{$_SERVER['PHP_SELF']}"); exit; case "save_regist": save_regist(); header("location:{$_SERVER['PHP_SELF']}"); exit; default: # code... break; } } catch (exception $e) { $error = $e->getMessage(); } -
若想知道更多方法,可參考:http://php.net/manual/en/language.exceptions.extending.php
-
我們可以把 $error 送到樣板檔(檔案最前面記得給$error一個預設值):
require_once 'smarty/libs/Smarty.class.php'; $smarty = new Smarty; $smarty->assign('name', $name); $smarty->assign('group', $group); $smarty->assign('op', $op); $smarty->assign('error', $error); $smarty->assign('page_title', '活動報名系統'); $smarty->display('index.tpl'); -
做一個新的樣板檔 \templates\alert_error.tpl,內容為:
<div class="alert alert-danger"> <h2>{$error}</h2> </div> -
接著在 index.tpl 主樣板檔中判斷是否有 $error,若有,引入上面的樣板檔,以呈現錯誤訊息。
<div class="col-md-9"> {if $error} {include file='alert_error.tpl'} {/if} </div>
8-3 註冊哪有這麼簡單!