:::

8-4 異常處理

  1. 遇到錯誤就直接die(),實際上並不太好。
    • 一來有些控制器可能還沒執行完或者沒有正常關閉。
    • 二來畫面實在很醜。
  2. 此時,我們可以利用PHP內建的異常處理機制。

一、拋出異常

  1. 把die()直接換成,如:throw new Exception()
    if (empty($name)) {
        throw new Exception("姓名為必填!");
    }
  2. 可用 Ctrl + H 來全部取代

  3. 有些在 or 後面的要改成:

    if (!$db->query($sql)) {
        throw new Exception($db->error);
    }

二、接收異常,並處理之

  1. 凡是有可能出現異常情形的,一般用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();
    }
  2. 若想知道更多方法,可參考:http://php.net/manual/en/language.exceptions.extending.php

  3. 我們可以把 $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');
  4. 做一個新的樣板檔 \templates\alert_error.tpl,內容為:

    <div class="alert alert-danger">
      <h2>{$error}</h2>
    </div>
    
  5. 接著在 index.tpl 主樣板檔中判斷是否有 $error,若有,引入上面的樣板檔,以呈現錯誤訊息。

    <div class="col-md-9">
      {if $error}
        {include file='alert_error.tpl'}
      {/if}
    </div>

     


:::

書籍目錄

展開 | 闔起

https%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D27%26tbdsn%3D724

計數器

今天: 4878487848784878
昨天: 3438343834383438
總計: 7395207739520773952077395207739520773952077395207