facebook twitter hatena line email

Php/exceptionメモ

提供: 初心者エンジニアの簡易メモ
2015年5月20日 (水) 03:12時点における127.0.0.1 (トーク)による版 (ページの作成:「==例外に使うexceptionの継承での使い方== try { throw new MyException("Err:001"); } catch (MyException $e) { print $e->getMessage(); } class MyExce...」)

(差分) ←前の版 | 最新版 (差分) | 次の版→ (差分)
移動: 案内検索

例外に使うexceptionの継承での使い方

try {
  throw new MyException("Err:001");
} catch (MyException $e) {
  print $e->getMessage();
} 
class MyException extends Exception
{
  public function MyException($message, $code = 0)
  {
    parent::__construct($message, $code);
    // print $this->message;// Err:001
    // print $this->code;  // 0
    // print $this->file;  // /home/test/exception.php
    // print $this->line;  // 4
    
    print nl2br(print_r(get_object_vars($this),1));
  }
}

こんな感じで使えるといいかも。

<?php
require_once 'Zend/Exception.php';
/**
 * AppException
 * 
 * @ex
 * throw new AppException(AppException::ERR_SAMPLE);
 */
class AppException extends Zend_Exception
{
    // エラーコード定数
    
    // 全体
    const ERR_DB_CONNECT                            = 5001;     // DBコネクションエラー
    
    /**
     * constructor
     */
    public function __construct($errCode, $addMessage = )
    {
        switch ($errCode)
        {
            case self::ERR_DB_CONNECT:
                $errMessage = 'DBコネクションエラー';
                break;
            /**
             * 予期せぬエラー
             */
            default:
                $errMessage = 'システムエラー';
                break;
        }
        // 追加メッセージがあるとき
        if ($addMessage) {
            $errMessage .= $addMessage;
        }
        parent::__construct($errMessage, $errCode);
    }
    /**
     * 表示用メッセージ作成
     */
    static public function makeMessage($errMessage, $errCode)
    {
        return 'Error:' . $errCode . ' ' . $errMessage;
    }
}