Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php custom exception handling

Tags:

exception

php

I am wanting to handle exceptions in my PHP application myself.

When I throw an exception I am wanting to pass along a title to be used in the error page.

Can someone please link me to a good tutorial, or write a clear explanation of how the exception handling actually works (eg how to know what sort of exception you are dealing with, etc.

like image 722
Hailwood Avatar asked Jan 19 '11 09:01

Hailwood


1 Answers

Official docs is a good place to start - http://php.net/manual/en/language.exceptions.php.

If it is just a message that you want to capture you would do it at follows;

try{
    throw new Exception("This is your error message");
}catch(Exception $e){
    print $e->getMessage();
}

If you want to capture specific errors you would use:

try{
    throw new SQLException("SQL error message");
}catch(SQLException $e){
    print "SQL Error: ".$e->getMessage();
}catch(Exception $e){
    print "Error: ".$e->getMessage();
}

For the record - you'd need to define SQLException. This can be done as simply as:

class SQLException extends Exception{

}

For a title and message you would extend the Exception class:

class CustomException extends Exception{

    protected $title;

    public function __construct($title, $message, $code = 0, Exception $previous = null) {

        $this->title = $title;

        parent::__construct($message, $code, $previous);

    }

    public function getTitle(){
        return $this->title;
    }

}

You could invoke this using :

try{
    throw new CustomException("My Title", "My error message");
}catch(CustomException $e){
    print $e->getTitle()."<br />".$e->getMessage();
}
like image 190
Matt Lowden Avatar answered Oct 13 '22 00:10

Matt Lowden