カスタム例外

MyException

 <?php
 class MyException extends Exception {
 
     private $message2 = '';
 
     function __construct($mesg, $mesg2) {
         parent::__construct($mesg);
         $this->message2 = $mesg2;
     }
 
     function getMessage2() {
         return $this->message2;
     }
 
     function getPretty() {
         $buf = array();
         $traceList = $this->getTrace();
         foreach ($traceList  as $idx => $v) {
             $file = $idx == 0 ? $this->getFile() : $traceList[$idx - 1]['file'];
             $line = $idx == 0 ? $this->getLine() : $traceList[$idx - 1]['line'];
             $class = isset($v['class'])    ? $v['class'] . '::'    : '';
             $func  = isset($v['function']) ? $v['function'] . '()' : '';
             $buf[] = sprintf('- %s%s, %s, %d', $class, $func, $file, $line);
         }
         $begin = array_pop($traceList);
         $buf[] = sprintf('- {main}, %s, %d', $begin['file'], $begin['line']);
         return implode("\n", $buf);
     }
 
 }

使用例

foo.php

 <?php
 function fooErr() {
     barErr();
 }

bar.php

 <?php
 function barErr() {
     $baz = new Baz;
     $baz->bazErr();
 }

Baz.php

 <?php
 class Baz {
     function bazErr() {
         throw new MyException('hello', 'world');
     }
 }

test.php

 <?php
 include('foo.php');
 include('bar.php');
 include('Baz.php');
 include('MyException.php');
 
 try {
     fooErr();
 } catch (Exception $e) {
     print $e->getMessage() . "\n";
     print $e->getMessage2() . "\n";
     print $e->getFile() . "\n";
     print $e->getLine() . "\n";
     //print_r($e->getTrace());
     print $e->getPretty() . "\n";
 }
 
 ------------------------------------------------------
 php ./test.php
 => hello
 => world
 => /home/taro/tmp/Baz.php
 => 4
 => - Baz::bazErr(), /home/taro/tmp/Baz.php, 4
 => - barErr(), /home/taro/tmp/bar.php, 4
 => - fooErr(), /home/taro/tmp/foo.php, 3
 => - {main}, /home/taro/tmp/test.php, 9

参考


トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS

Last-modified: 2011-03-24 (木) 15:32:52