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

(This post was last modified: 09-21-2015, 04:29 PM by jLinux.)

(09-21-2015, 03:55 PM)includebeer Wrote: I always use exceptions in my models and libraries. The controllers do the try/catch and return the errors ...

Exactly what Im thinking about doing

Right now, this is the class for notifications
PHP Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class 
App_lib
{
 
   /**
     * @var string $notifications   Array of notifications
     */
 
   private static $notifications = array();

 
   private static $CI;

 
   public static $instance;

 
   // ------------------------------------------------------------------------

 
   public function __construct()
 
   {
 
       self::$CI =& get_instance();

 
       static::$instance $this;

 
       $this->_check_flash_notifications();
 
   }
 
   
    
// ------------------------------------------------------------------------

 
   public static function keep_flash_notifications()
 
   {
 
       self::$CI->session->keep_flashdata('notifications');
 
   }

 
   // ------------------------------------------------------------------------

 
   private static function set_flash_notifications()
 
   {
 
       self::$CI->session->set_flashdata('notifications'self::$notifications);
 
   }

 
   // ------------------------------------------------------------------------

 
   private function _check_flash_notifications()
 
   {
 
       $flash self::$CI->session->flashdata('notifications');

 
       if($flash)
 
       {
 
           if(empty(self::$notifications))
 
           {
 
               self::$notifications $flash;
 
           }
 
           else
            
{
 
               self::$notifications array_merge(self::$notifications$flash);
 
           }
 
       }
 
   }

 
   // ------------------------------------------------------------------------

 
   /**
     * Add Notification
     *
     * Add a notification to the private $notifications array
     *
     * @param   string     $type       Type of notification (error, success, info, warning)
     * @param   string     $message    Notification message value
     * @param   bool    $log        If TRUE, then log_message($type, $message) will ensue
     *
     */
 
   public static function add_notification($type 'info'$title NULL$message$log FALSE)
 
   {

 
       if( ! in_array($type, ['error','info','success','warning']))
 
       {
 
           log_message('error',"Unknown notification type '{$type}' for message: {$message}; Changing type to info");

 
           $type 'info';
 
       }

 
       self::$notifications[$type][] = array($title$message);

 
       if($loglog_message($type$message);

 
       self::set_flash_notifications();
 
   }

 
   // ------------------------------------------------------------------------

 
   /**
     * Clear Notifications
     *
     * Clears private $notifications array
     *
     */
 
   public static function clear_notifications()
 
   {
 
       self::$notifications = array();
 
   }

 
   // ------------------------------------------------------------------------

 
   /**
     * Get Notifications
     *
     * Returns local private $notifications array
     *
     * @since   0.1.0
     * @return  arr         Array of notifications
     *
     */
 
   public static function get_notifications()
 
   {
 
       log_message('error','Executed: get_notifications');

 
       $return self::$notifications;

 
       self::clear_notifications();

 
       return $return;
 
   }

 
   // ------------------------------------------------------------------------

 
   /**
     * Get Latest Error
     *
     * This will retrieve all errors using the self::get_notifications function, meaning it will
     * clear out all notifications, but return only one...
     *
     * @since   0.1.0
     * @return str
     */
 
   public static function get_latest_errors()
 
   {
 
       log_message('error','Executed: get_latest_errors');

 
       if( ! $notifications self::get_notifications())
 
       {
 
           return FALSE;
 
       }

 
       //die('<pre>' . print_r($notifications, TRUE));

 
       if(@count($notifications['error']) > 1)
 
       {
 
           $return = array();

 
           foreach($notifications['error'] as $n)
 
           {
 
               // Push just the error string to the array
 
               array_push($return$n[1]);
 
           }

 
           return implode('; ',$return);
 
       }
 
       elseif(@count($notifications['error']) === 1)
 
       {
 
           // Return just the error string
 
           return $notifications['error'][0][1];
 
       }
 
       elseif( ! @isset($notifications['error'][0]))
 
       {
 
           return FALSE;
 
       }

 
       // Just incase
 
       return FALSE;
 
   }

 
   // ------------------------------------------------------------------------

 
   /**
     * Check Errors
     *
     * Checks for any errors in private $notifications array
     *
     * @since   0.1.0
     * @return  bool        TRUE of self::$notifications['error']
     *
     */
 
   public static function check_errors()
 
   {
 
       if(isset(self::$notifications['error']))
 
       {
 
           return TRUE;
 
       }

 
       return FALSE;
 
   }

 
   // ------------------------------------------------------------------------

 
   /**
     * Check Notifications
     *
     * Check for any created notifications have been added to $notifications
     *
     * @since   0.1.0
     * @return  bool        TRUE if self::$notifications isnt empty
     *
     */
 
   public static function check_notifications()
 
   {
 
       return (self::$notifications TRUE FALSE);
 
   }

 
   // ------------------------------------------------------------------------

 
   /**
     * Generate Notifications
     *
     * Uses functions in the template helper to generate the output for any
     * notifications
     *
     * @since   0.1.0
     * @return  string        String containing HTML for notifications
     *
     */
 
   public static function generate_notifications()
 
   {
 
       $return '';

 
       foreach(self::get_notifications() as $type => $n)
 
       {
 
           if(function_exists('notification_' $type))
 
           {
 
               $f 'notification_' $type;

 
               if(is_array($n))
 
               {
 
                   foreach($n as $n2)
 
                   {
 
                       $return .= $f($n2[0], $n2[1]);
 
                   }
 
               }
 
               else
                
{
 
                   $return .= $f($n[0], $n[1]);
 
               }
 
           }
 
       }

 
       return (empty($return) ? NULL $return);
 
   }


I know, its terrible... use kind words.

And this is how the travesty its used..
PHP Code:
// Create a notification/alert
App_lib::add_notification('error','Title','Some text');

if( ! 
somefunction() AND ! App_lib::check_errors()){
 
   App_lib::add_notification('error','Title','Something failed, not sure what though, since no notification/error/alert was generated');
}

// Show em
echo "Errors: " App_lib::generate_notifications(); 

Id much rather just do something like..
PHP Code:
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);

(Thats just me playing around with the idea..)

If ErrorException or Exception shouldn't be used, I can create my own (http://php.net/manual/en/language.exceptions.php#91159)
Reply


Messages In This Thread
RE: Handing errors in my code using Exceptions - by jLinux - 09-21-2015, 04:21 PM



Theme © iAndrew 2016 - Forum software by © MyBB