PHP errors as exceptions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
xtiano77
Forum Commoner
Posts: 72
Joined: Tue Sep 22, 2009 10:53 am
Location: Texas

PHP errors as exceptions

Post by xtiano77 »

I am stuck. I am trying to figure out how to setup a class that will handle PHP errors as exceptions. I reviewed the PHP Manual, specifically the "ErrorException" class, but I am having a hard time figuring out how to implement the method without having to call the "set_error_handler()" from outside a class. The code below what what I copied from the PHP manual:

Code: Select all

 
<?php
class ErrorHandler extends Exception {
    protected $severity;
   
    public function __construct($message, $code, $severity, $filename, $lineno) {
        $this->message = $message;
        $this->code = $code;
        $this->severity = $severity;
        $this->file = $filename;
        $this->line = $lineno;
    }
   
    public function getSeverity() {
        return $this->severity;
    }
}
 
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorHandler($errstr, 0, $errno, $errfile, $errline);
}
 
set_error_handler("exception_error_handler", E_ALL);
 
function A() {
    $foo->bar; // Purposely cause error
}
 
function B($c) {
    A();
}
 
try {
    B('foobar');
} catch (Exception $e) {
    var_dump($e->getTrace());
}
?>
 
Can someone shed some light on this? Thanks in advance for your help.
Last edited by xtiano77 on Thu Nov 05, 2009 7:20 am, edited 1 time in total.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP errors as exceptions

Post by requinix »

If you want to catch errors you have to use set_error_handler (which you can call from anywhere) and some kind of exception.

What's the question?
xtiano77
Forum Commoner
Posts: 72
Joined: Tue Sep 22, 2009 10:53 am
Location: Texas

Re: PHP errors as exceptions

Post by xtiano77 »

I wanted to know if it was possible to include the "set_error_handler()" as part of a class definition. Anyway, I tried it out right under the "require_once()" and it worked just fine. Maybe there is a better way to do it, but I guess I'll continue this way until I get there. Thanks anyway for the advice. Cheers!

Code: Select all

 
<?php
session_start();
require_once("MyException.php");
set_error_handler(array(MyException, "handleException"));
class BasicPage {
 
// rest of class definition...
 
}
?>
 
P.S. How do you resolve a post?
Post Reply