Error Handler

From PHPDevShell

Jump to: navigation, search

Error handling in PHPDevShell

PHPDevShell is build on a master error handler throwing and catching, it will catch and stop any uncaught thrown exceptions. It does have a graceful error handler too that a developer can use in its own classes for maximum error effectiveness.

a Simple graceful error handling situation:

// Lets create a simple function that throws out errors.
public function age ($age) 
{
    if ($age < 18) {
        // Note we are throwing to error and not Exception as out error handler is graceful.
        throw new error('You are too young!');
    }   
}

Right now we have a method with the ability to throw out an exception, so how will we utilise this?

// The code that uses this method should look something like this.
try {
    age(17);
} catch (error $e) {
    // Show warning without line and file information.
    $e->warning();
    // Show warning without line and file information.
    //$e->warningMessage();
}
 
// You also have these available in your catch block:
$e->warningMessage();
$e->noticeMessage();
$e->criticalMessage();
$e->warning();
$e->notice();
$e->critical();

All uncaught error will eventually be catched by the Master Error handlers, so no worries there.

Catching normal throw Exceptions

We could take the exception handling a step further, by catching normal Exceptions inside third party classes and handling the errors on our own:

// Simple function to throw a default exception.
function test1 ($age)
{
	if ($age < 18) {
		throw new Exception('You are too young you little shit.');
	}
}
 
// Second level functions and exception handler.
function test2 ($gender) {
	if ($gender != 'female') {
		throw new error('Only girls allowed here my man.');
	} else {
		try {
				throw new error('Wow another throw inside a throw.');
				test1(17);
			} catch (Exception $e) {
				throw new error($e->getMessage());
			}
	}
}
 
// Lets see how we can throw exceptions, wether in a method or function one could do.
try {
	test2('female');
} catch (error $e) {
	$e->warning();
}