Welcome Guest, Not a member yet? Register   Sign In
Handing errors in my code using Exceptions
#1

I was wondering how many of you use PHP ErrorException (or just Exception) to manage errors in your scripts. The way im managing Errors/Notifications/Logging is just really messy, and I was looking for an efficient way to clean it up.

I was thinking that maybe I could just throw exceptions from the Models or Libraries if an error is encountered, as opposed to just returning false.

Just to give an idea of what I mean by using the exceptions with notifications..
PHP Code:
<?php
class App_lib {
    private static function 
_display_notification($type$message)
    {
        echo 
strtoupper($type) . ": {$message}\n";
    }

    public static function 
add_notification($message$type 'info')
    {
        if(
$message instanceof ErrorException)
        {
            
self::_display_notification('error',"{$message->getMessage()}; Code: {$message->getCode()}; Severity: {$message->getSeverity()}print_r($message->getTrace(), TRUE) );
        }
        elseif(
$message instanceof Exception)
        {
            
self::_display_notification('info'$message->getMessage());
        }
        else
        {
            
self::_display_notification($type$message);
        }
    }

    public static function 
something($a)
    {
        if( ! 
is_numeric($a))
        {
            throw new 
ErrorException("The value $a is NOT numeric..",123,456);
        }

        if(
$a 2)
        {
            throw new 
Exception("The value $a was greater than 2");
        }

        if(
$a === 2)
        {
            return 
FALSE;
        }

        return 
TRUE;
    }
}

$val 'a';

try {
    if(
App_lib::something($val))
        echo 
"Value was apparently 1!\n";
    else
        echo 
"Value was 2\n";
}
catch(
Exception $e) {
    
App_lib::add_notification($e);
}

/*
 * Result..
 * $var = 'ABC';
 *      ERROR: The value ABC is NOT numeric..; Code: 123; Severity: 456
 *
 * $var = 3;
 *      INFO: The value 3 was greater than 2
 *
 * $var = 2;
 *      Value was 2
 *
 * $var = 1;
 *      Value was apparently 1!
 */

// Creating errors without using exceptions
App_lib::add_notification('info','Info notification');

App_lib::add_notification('error','error notification'); 

Anyone use them like this? If not, why not?
Reply


Messages In This Thread
Handing errors in my code using Exceptions - by jLinux - 09-17-2015, 09:54 PM



Theme © iAndrew 2016 - Forum software by © MyBB