SitePoint Sponsor

User Tag List

Results 1 to 24 of 24
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2004
    Location
    Brazil,Maringá-PR
    Posts
    128
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    adv. Error Handler in php4

    Looking this forum, I didn't found a good discussion about error handler in php4. Since moving to php5 will take some months to almost everybody, I'm sugesting here a discussion about this topic that many programmers let as the last one.
    Here goes a simple example class that I would like discussing how to handle the possible errors.
    PHP Code:
    class ArrayList{
        var 
    $file '';
        var 
    $data = array();
        var 
    $newLine "\r\n";
        
        function 
    ArrayList($options = array()){
            foreach(
    $options as $property=>$value):
                if( isset(
    $this->{$property}) ):
                    
    $this->{$property} = $value;
                else:
                    
    // raise notice: property no allowed
                
    endif;
            endforeach;
        }

        function 
    load(){
            
    $content file_get_contents($this->file);
            
    $this->data explode($this->newLine$content);
        }

        function 
    save(){        
            
    $rawData implode($this->newLine,$this->data);
            
    $fp fopen($this->file'w');
            
    fwrite($fp$rawData);
            
    fclose($fp);
        }
    }

    // class to force common errors
    class ForceErrors{
        function 
    wrongConstructorDataType(){
            
    $options 'not an array';
            
    $foo = new ArrayList($options);
        }

        function 
    wrongConstructorArrayKey(){
            
    $options = array('wrong_key'=>'foo');
            
    $foo = new ArrayList($options);
        }

        function 
    wrongConstructorArrayValues(){
            
    $options['file'] = 'invalid?file|name';
            
    $options['data'] = 'this should be an array';
            
    $options['data'] = 'this can not be a new line string';
            
    $foo = new ArrayList($options);
        }

        function 
    fileNotExistsOnLoad(){
            
    $options['file'] = 'file/not/exists.txt';
            
    $foo = new ArrayList($options);
            
    $foo->load();
        }

        function 
    canNotCreateFileOnSave(){
            
    $options['file'] = 'bad?file!name';
            
    $options['data'] = array('bar','foo');
            
    $foo = new ArrayList($options);
            
    $foo->save();
        }

    As you can see, since php is typeless, many errors can happen with bad use of the class, or wrong user input. The other kind of error happens cause external resources like file that don't has permission to read or write, and so on.

    Solutions using PearErrorStack are welcome

    Who's the first?

  2. #2
    SitePoint Addict silent's Avatar
    Join Date
    Jun 2004
    Location
    Roaming North America
    Posts
    220
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Maybe I sound old-fashioned, but why not use PHP4's built-in error handling functions (error_reporting() and set_error_handler()) and simply use PHP4's trigger_error()? In the initialization of all my applications, I have something like:
    PHP Code:
    error_reporting(E_ALL); /* or E_ALL ~ E_NOTICE for non-debug... */
    set_error_handler("ErrorHandler"); 
    then, in a separate file, I have an error handler that handles the different errors the way I need them to...
    PHP Code:

    /** 
     * Logs or reports errors.
     *
     * @access    public
     * @return     void
     * @param    int        type of error
     * @param    string    error message
     * @param    string    filename
     * @param    int        line number
     * @param    array    array of environment variables
    */
    function ErrorHandler($ErrorType$ErrorMessage$FilePath$LineNo$Context) {

    /* 
      Depending on configuration variables and error type, 
      logs (to file or db) the error, or displays the error to 
      the developer/user, or simply lets the error go...
    */


    and in my API, if I have an error that occurs in a class that requires action, I simply issue trigger_error():
    PHP Code:
    class SomeClass {
      function 
    SomeFunction(&$SomeObject) {
        
    /* Assert required param */
        
    if (get_class($SomeObject) != 'requiredobjectclass') {
          
    trigger_error("Expected 'requiredobjectclass' not supplied"E_USER_ERROR);
          return 
    false;
        }
        
    /* Else, go on... */
      
    }

    This way, you use the error handling functionality that PHP4 comes with, instead of trying to re-invent the wheel (like PEAR does). One of developers' biggest complaints about PEAR is working with its Error handling. Why? Because it re-invents the wheel and forces the developer to work with PEAR's custom error object, instead of "throwing" (PHP4's trigger_error()) the error and letting the developer work with the error the way they want to...

    just my opinion,

    jay

  3. #3
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thats the same thing i do.
    I set error_reporting(E_ALL); and inside my errorhandler i then push the errors unto a stack for all non-fatal errors.
    In my code i generally trigger an error of level E_USER_WARN, and return. If the code consists of several layered models, they will each detect that an error has ocurred, retrigger a new error and return. On the top level i "catch" the error and triggers a E_USER_ERROR (fatal). tis way, i get a stack of errors, so that i can track the error from the innermost (often on the database-level) out to the controller-level of my application.

  4. #4
    Non-Member
    Join Date
    Jan 2004
    Location
    Planet Earth
    Posts
    1,764
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)


    Terrible business this not having Exceptions though

    PHP Code:
    trigger_error( ... ); 
    Is the next best thing to it I suppose, and since we're all posting examples today, why not ?

    PHP Code:
    # index.php
    ...
    //-- utility functions
        
        
    function ErrorHandler$num$msg$file$line ) {
            
    $e = &new ErrorReporter;
            
    $e -> Dump( array( 
                
    'message'    =>    (string) $msg
                
    'type'        =>    (int) $num
                
    'file'        =>    (string) $file
                
    'line'        =>    (int) $line ) );
            
            
    $e -> Generate();
            
            die();
        }
    ... 
    PHP Code:
    class ErrorReporter {
            var 
    $errors;
            
            function 
    ErrorReporter() {
            }
            
            function 
    Dump$errors ) {
                if( 
    is_array$errors ) ) {
                    
    $this -> errors $errors;
                }
            }
            
            function 
    Generate() {
                
    $flags explode'|'LOGGING_LEVEL );
                
                foreach( 
    $flags as $flag ) {
                    
    $flag trim$flag );
                    
                    switch( 
    $flag ) {
                        case 
    'LOG'
                            require_once( 
    SYS_ROOT.LIB_XML );
                            
                            
    $f pathinfo$this -> errors['file'] );
                            
                            
    $log = &new XmlLoggerLOGGING_DIRECTORY );
                            
    $log -> Define( array( 
                                
    'type'            =>    $this -> errors['type'],
                                
    'line'            =>    $this -> errors['line'],
                                
    'file'            =>    $f['basename'],
                                
    'message'        =>    $this -> errors['message'],
                                
    'pathname'        =>    $f['dirname'],
                                
    'timestamp'        =>     dateDATE_TIMESTAMPtime() ) ) );
                            
                            
    $log -> AppendLog();
                            
    $log -> Save();
                            
                            break;
                        
                        case 
    'DISPLAY':
                            
    header'location:'.REDIRECT_ERRORS ); 
                            die();
                            
                            break;
                            
                        default:
                            break;
                    }
                }            
            }
        } 

  5. #5
    SitePoint Zealot
    Join Date
    Jul 2004
    Location
    Brazil,Maringá-PR
    Posts
    128
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Cool

    Hi silent, I agree that the native error_handler is the best way to follow.
    but I think that is missing the stack that kyberfabrikken suggest. That's why I suggest PearStackError.
    In those examples, everybody show how to log, display, die or redirect, but no example about how "HANDLE" the error.
    Stop the script on errors isn't always the best way. I want know how can I test if an error happens and handle this in a clever way. And How can I design my class to minimize opens for errors.

  6. #6
    SitePoint Addict myrdhrin's Avatar
    Join Date
    Jul 2004
    Location
    Montreal
    Posts
    210
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Trying to get closer to the try/catch approach

    I've used an approach on some of my new projects... it still needs to mature but the idea works for me.

    If you ever used the try/catch functionality in c++ you'll get what I mean.

    First I have this class (that's the one I used on a project called online timesheet)

    TSError.class.inc
    PHP Code:
    <?php
    /**************************************************************************
    * :NAME: TSError.class.inc
    * :CLASS: 
    * :PURPOSE:
    * The error handling object for the timesheet project
    * **************************************************************************/

    define 'TSError_CLASS_NAME''tserror' );

    class 
    TSError
    {

        var 
    $Code// STRING: The error code for programmatic use
        
    var $Source// STRING: The name of the module that triggered the error
        
    var $Parameters// ARRAY.STRING: The parameters of the error.  False if no parameters

        
    var $Predecessor// TSError: The error at the origin of this error.

        /*
        *    :NAME: TSError
        *    :CONSTRUCTOR:
        *    :PURPOSE:
        *       set the error to it's initial parameters
        *    :NOTE:
        *       The fourth parameter is not declared being optional but can be 
        */
        
    function TSError($Code$Source$Predecessor$Parameters)
        {
            
    $this->Code $Code;
            
    $this->Source =  $Source;
            
    $this->Parameters $Parameters;
            
            
    $this->Predecessor $Predecessor;

        }
        
        
    /*
        *    :NAME: IsError
        *    :STATIC.FUNCTION:
        *    :PURPOSE:
        *       Determine if the value given to the function is an error
        */
        
    function IsError(&$var)
        {

            if (
    gettype($var) == 'object')
            {       

                if (
    get_class($var) == TSError_CLASS_NAME)
                {
                    return 
    TRUE// it is an error
                
    }
            } 
            
            return 
    FALSE;  // not an error object 

        
    }
        
    }


    ?>
    Then whenever I have code that could raise an error I'll do the following:

    PHP Code:
    if (!TSError::IsError($e functionThatTriggerAnError())
    {
       
    // code with no error
    } else { // An error got triggered... catch it with $e
       // code to process the error using the $e->Code and other attributes

    I know it's still very far from being perfect... for a first I'd love to be able to really Raise errors but it helps a lot when trying to do inline error processing. The biggest drawback I've found with it is that any function that would "return" a value should rather return it as a value passed in reference instead of by value... but once you get used to the style it's not such a big problem.

    Notice that the TSError class not does have any description, only a code and parameters... this way I'm staying away from language specific error messages but I can do more processing based on the error code (that I preferably document before hand).



    You can also "list" multiple errors since every error you create can have a predecessor (so you create more generic errors than can be "explored" if you need more detail).

    Anyway... just my 2 cents
    Jean-Marc (aka Myrdhrin)
    M2i3 - blog - Remind-M

  7. #7
    SitePoint Addict silent's Avatar
    Join Date
    Jun 2004
    Location
    Roaming North America
    Posts
    220
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by WidowMaker
    ... Exceptions
    I agree, but we are specifically talking PHP4 here

    Quote Originally Posted by myrdhrin
    I've used an approach on some of my new projects... it still needs to mature but the idea works for me.

    If you ever used the try/catch functionality in c++ you'll get what I mean.
    I think it is a bad idea to try to emulate language-level processing such as try/catch statements in an object hierarchy. I get what you are trying to do, but I go back to my first statement that this is what bugs the heck out of developers who have to work with other people's code (PEAR!). You are stuck using an object model for error reporting that a) doesn't really fit with the language constructs inherent in the language, b) now the developer has to learn a whole new set of things just to "handle" errors in your application, and c) most of the time, you are not dealing with an "error", but instead, a "situation", which is more gracefully, and systematically, handled using logic and return values within grouped classes and functions.

    To me, "errors" are things that are show stoppers. Period. I have never really been a fan of "error stacks". Why? Because what is the thing you actually look for in an error stack, 99 times out of 100? The root error! I can't stand it when I see Java server pages, badly coded, which output a "stack trace". Fooey. The only thing the developer is really interested in is what caused the error. What's the purpose of seeing an "error stack", when all the non-root errors are simply errors derived from the root error? You fix the root problem, and the other errors disappear, unless of course, they are show stoppers as well.

    My point (opinion, of course) is this: PHP4's error handling works just fine. PHP5's throw/catch paradigm works fine as well. Use one language's constructs the way they were intended. Don't try to invent the other language's constructs just because "they're better."

    cheers,

    jay

    [open]can of worms?[/open]

  8. #8
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    here is a somehow simplified version of my preferred errorhandling-mechanism.
    error_handler.php
    PHP Code:
    <?php
    $GLOBALS
    ['error_handler_stack'] = array();
    $GLOBALS['error_handler_failat'] = 0;    // fails at fatal errors, but continue at warnings
    error_reporting(E_ALL);
    set_error_handler('create_error');

    function 
    create_error($errno$errstr$errfile$errline)
    {
        
    // determine errortype
        
    switch ($errno) {
            case 
    :
            case 
    :
            case 
    16 :
            case 
    64 :
            case 
    256 :
                
    // level = error
                
    $errlevel 0;
                break;
            case 
    :
            case 
    32 :
            case 
    128 :
            case 
    512 :
                
    // level = warning
                
    $errlevel 1;
                break;
            case 
    :
            case 
    1024 :
                
    // level = notice
                
    $errlevel 2;
                break;
        }
        
    // push error to stack
        
    $GLOBALS['error_handler_stack'][] = array(
                
    'errno' => $errno,
                
    'errstr' => $errstr,
                
    'errfile' => $errfile,
                
    'errline' => $errline,
                
    'errlevel' => $errlevel
            
    );
        
    // halt execution i fneed be
        
    if ($errlevel <= $GLOBALS['error_handler_failat']) {
            
    halt();
        }
    }

    function 
    is_error()
    {
        return 
    count($GLOBALS['error_handler_stack']) > 0;
    }

    function 
    halt()
    {
        
    // clear buffers
        
    while (ob_get_level() > 0ob_end_clean();
        
    // print error stack
        
    $errortypes = array( => 'Error'=> 'Warning'=> 'Notice');
        echo 
    "<h1>an error has occurred</h1><em>error stack trace :</em><ul>";
        foreach (
    $GLOBALS['error_handler_stack'] as $e) {
            echo 
    "<li><strong>(" $errortypes[$e['errlevel']] . " #".$e['errno'] . ")</strong> ".htmlentities($e['errstr']);
            echo 
    "<br />In line " $e['errline'] . " of file " $e['errfile'] . "</li>";

        }
        echo 
    "</ul>";
        
    // stop execution
        
    exit(-1);
    }
    ?>
    And some samplecode, that generates an error.
    example.php
    PHP Code:
    <?php
    require_once('error_handler.php');

    function 
    foo()
    {
        
    $result divide(1000);
        if (
    is_error())
            return 
    trigger_error("Oh my. Something went terrible wrong."E_USER_WARNING);
        return 
    $result;
    }

    function 
    divide($a$b)
    {
        if (
    $b == 0)
            return 
    trigger_error("Division by zero.."E_USER_WARNING);
        return 
    $a $b;
    }

    foo();
    if (
    is_error())
        
    halt();
    ?>
    The above scripts produce the following output.
    an error has occurred
    error stack trace :
    (Warning #512) Division by zero..
    In line 84 of file C:\FoxServ\www\foo.php
    (Warning #512) Oh my. Something went terrible wrong.
    In line 77 of file C:\FoxServ\www\foo.php

    This is often quite usefull information for debugging, since it is possible to determine not only where an error ocurred, but also witch piece of code is responsible for producing the error.
    In the above example halting execution in divide() would inform you that the function had been called wrongly, but would keep you in the dark as to why this did happen. By using a stack to store a chain of errors, it becomes clear where the error origins.

  9. #9
    SitePoint Zealot
    Join Date
    Jul 2004
    Location
    Brazil,Maringá-PR
    Posts
    128
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    myrdhrin, your solution is similar to what pear does. But I still think that the solution is around error_handling, since I can catch errors that happens inside classes that don't use your error class.
    Quote Originally Posted by silent
    I think it is a bad idea to try to emulate language-level processing such as try/catch statements in an object hierarchy.
    I think php error_handling is excellent for logging, displaying and debugging, but need some adjusts to "HANDLE SITUATIONS".
    Quote Originally Posted by silent
    most of the time, you are not dealing with an "error", but instead, a "situation"
    You found a word that resume this thread. "HANDLING SITUATIONS"
    Quote Originally Posted by silent
    which is more gracefully, and systematically, handled using logic and return values within grouped classes and functions.
    I think just returning values is not aproprieate to handle errors where I would need to know the error message, the error level and so on.
    Quote Originally Posted by silent
    The only thing the developer is really interested in is what caused the error. What's the purpose of seeing an "error stack", when all the non-root errors are simply errors derived from the root error? You fix the root problem, and the other errors disappear, unless of course, they are show stoppers as well.
    This I have to disagree. Many times a call at the root is ok, but with a stack you can discovery that a "function that build a query" can not handle the "NULL" type. But it's justing usefull for logging and/or debugging. This discussion is more about handle errors that eventualy happens, like lost connection, some resource busy or locked or with no permission.
    Quote Originally Posted by silent
    My point (opinion, of course) is this: PHP4's error handling works just fine.
    my wish with this thread is to found a definitive way to handle situations, not justing logging them.

  10. #10
    SitePoint Addict silent's Avatar
    Join Date
    Jun 2004
    Location
    Roaming North America
    Posts
    220
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by neves
    This I have to disagree. Many times a call at the root is ok, but with a stack you can discovery that a "function that build a query" can not handle the "NULL" type. But it's justing usefull for logging and/or debugging.
    I'm having trouble understanding this statement...please explain.
    Quote Originally Posted by neves
    This discussion is more about handle errors that eventualy happens, like lost connection, some resource busy or locked or with no permission.
    My bad. I don't believe any of those things are errors...
    Let's take the resource busy, for example. I think a function, let's call it GetResource() should return either the resource, or false. An optional parameter of $Error could be filled with a description of the reason the resource was not returned (similar to the fsockopen() function). That way, you give the ability to the calling developer to handle the situation the way they want, instead of trapping them in using your object model for something as low-level as "error-handling". This allows the developer (again, similar to the fsockopen() function) to do (or not do) with the "error" what they wish.
    my wish with this thread is to found a definitive way to handle situations, not justing logging them.
    My point was just that: that, to me, the definitive way to handle "situations", or errors, is to leave it up to the developer using your code. If someone else has to use it, stick with PHP4 or PHP5's inherent low-level mechanisms for triggering or throwing errors, and if there is a "situation", like a locked resource that you wish to give the ability to the programmer to determine what the cause was, then give them the option of passing in an error parameter by reference, and filling that in your function.

    hope I have made myself clear; I only meant to emphasize that for people using other people's code, it's best to stick with what the eventual developer will understand in regards to the underlying language's inherent style and ability...

    jay

  11. #11
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ... for people using other people's code, it's best to stick with what the eventual developer will understand in regards to the underlying language's inherent style and ability...
    I totally agree on this point. As a developer, it feels frustratingly intrusive to be forced to use someone elses framework, when trying to incorporate a piece of code into your own. This is probably the main reason why i'm personally not a fan of PEAR. Whenever i need to use some component from that repository, i have to clean the code of the errorhandling mechanism. If only PEAR had stuck with the inherent errorhandler of php4, this wouldn't be a problem.

  12. #12
    SitePoint Zealot
    Join Date
    Jul 2004
    Location
    Brazil,Maringá-PR
    Posts
    128
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Lightbulb

    Hi Silent, sorry my ugly english
    I mean that a stack with the path from the root to the error is excelent for debugging and logging. But this stack can be the debug_backtrace !!!

    I totally agree that the code must be more tied to the php and not to a specific class.

    I would be glad if somebody could show us how to handle the errors that can happen on the class (ArrayList) that I post on the top. But it must be a pattern, cause I want to repeat the solution on every code that I do.

    I still think that using PHP4 error_reporting is enouth. I just don't know how?

  13. #13
    ********* Victim lastcraft's Avatar
    Join Date
    Apr 2003
    Location
    London
    Posts
    2,423
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hi...

    Quote Originally Posted by neves
    Looking this forum, I didn't found a good discussion about error handler in php4.
    It's actually a poor choice of subject . You should be trying to prevent errors, not logging them, filing them, cataloguing them, filtering them, redirecting them, intercepting them, piping them, queuing them or stacking them. Who cares on the exact order of errors if you shouldn't be getting any in the first place .
    Pouring over error logs is a spectacularily inefficient way to write code. The time you invest in this could be spent in unit testing, code review or a complete rewrite. The result will be less code and a more elegant solution. Also one that is easier to deploy because you don't have to worry about the location and permissions of error files (which usually end up in a config file and so on). No one ever looks at errors anyway. It's just code bloat...which makes the code harder to work with...that produces more errors...that have to be logged...

    Error handling is a favourite way for IT people to generate work for themselves.

    As developers we are often drowning in complexity. To master this complexity we use encapsulation to forget about the details. If you buy a car you want to get from place to place without constantly having to monitor the temperature gauge. Monitoring for errors is similar and leaks through our encapsulation. If you have had a car like that (or several in my case), for your own sanity you get it fixed ASAP. Likewise, a piece of software with lot's of error handling makes me nervous. It feels dodgy.

    If you statically analize the code with at least one other person, all your failure modes should be converted to some kind of return value. Even exceptions should be used lightly as they blow away any chance of recovery. They should be, well, exceptional. If you enforce your careful analysis with an automated test suite, you should prevent future breakages. A zero defect policy is not just good for manufacturing, it's good for software too.

    yours, Marcus
    Marcus Baker
    Testing: SimpleTest, Cgreen, Fakemail
    Other: Phemto dependency injector
    Books: PHP in Action, 97 things

  14. #14
    eschew sesquipedalians silver trophy sweatje's Avatar
    Join Date
    Jun 2003
    Location
    Iowa, USA
    Posts
    3,749
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Don't beat around the bush Marcus, tell us how you really feel
    Jason Sweat ZCE - jsweat_php@yahoo.com
    Book: PHP Patterns
    Good Stuff: SimpleTest PHPUnit FireFox ADOdb YUI
    Detestable (adjective): software that isn't testable.

  15. #15
    ********* Victim lastcraft's Avatar
    Join Date
    Apr 2003
    Location
    London
    Posts
    2,423
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hi...

    Quote Originally Posted by sweatje
    Don't beat around the bush Marcus, tell us how you really feel
    OK, I was a bit harsh wasn't I?

    If I am a bit evangelical about this, it's because once you have seen things done a better way, it's just so painful to see other people going around in circles.

    yours, Marcus
    Marcus Baker
    Testing: SimpleTest, Cgreen, Fakemail
    Other: Phemto dependency injector
    Books: PHP in Action, 97 things

  16. #16
    eschew sesquipedalians silver trophy sweatje's Avatar
    Join Date
    Jun 2003
    Location
    Iowa, USA
    Posts
    3,749
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by lastcraft
    OK, I was a bit harsh wasn't I?
    Not harsh, just poignant.

  17. #17
    SitePoint Addict silent's Avatar
    Join Date
    Jun 2004
    Location
    Roaming North America
    Posts
    220
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by sweatje
    Not harsh, just poignant.
    And I thought I was being harsh above! Marcus, you echo my sentiments exactly. Only, as usual, quite a bit more eloquently than I could put it.

    cheers,

    jay

  18. #18
    SitePoint Zealot
    Join Date
    Aug 2003
    Location
    Sydney
    Posts
    187
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As Marcus mentioned, time is better spent making the code work than worrying about future errors if any. At the moment all I do is catch errors in their respective classes and pass them up through the heirachy of classes. This way it is easy for me to display a page with the error without leaving it in a disgusting state as to not scare the client. But I rarely finish a project thinking that errors will pop up as I test vigorously before handing it over. And most importantly I test it in their setup as this does make sure that the code does work in their environment.

    Unlike Marcus I dont use Unit Testing, as of yet, mainly because I havent read up on it and specifically his Unit Testing article in phparch.

  19. #19
    SitePoint Addict myrdhrin's Avatar
    Join Date
    Jul 2004
    Location
    Montreal
    Posts
    210
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by silent
    You are stuck using an object model for error reporting that a) doesn't really fit with the language constructs inherent in the language, b) now the developer has to learn a whole new set of things just to "handle" errors in your application, and c) most of the time, you are not dealing with an "error", but instead, a "situation", which is more gracefully, and systematically, handled using logic and return values within grouped classes and functions.
    I would not say I'm stuck... I still use the native error reporting when I need error reporting and cases where an error occurs that I did not think of having logic to process. (better that and display a nice "oups... we just had a problem. Hope it did not cause any trouble" than plain PHP and SQL error messages).

    b) It's still not a public library, nor a standard... fell free not to use it *grin*
    Altough I'd say that this way of reporting "situations" allows for a more documented interface and more information on what the problem is exactly since every "situation" can have different parameters that can be act upon (or reported in different ways).

    c) That I totally agree with you... The terminology for the class is not appropriate. I did a lot of thinking as should I call it "return something" or "error something" or "something something" (you get the idea). I stopped my choice on error since "situation" did not seem right in the code and the purpose was to process "exceptions"... not sucess (hey!!! exception would be a better word).

    Quote Originally Posted by silent
    To me, "errors" are things that are show stoppers. Period.
    Hum... if you can't recover from an error... yes it's a show stopper and the PHP4 way of handling it would be ok... an error you can recover (by deleting a file, or testing a second server) are no show stopper even if they are error.

    I think we'd need to clarify terminology so we can talk using a comon terminology.

    Quote Originally Posted by silent
    I have never really been a fan of "error stacks". Why? Because what is the thing you actually look for in an error stack, 99 times out of 100? The root error! I can't stand it when I see Java server pages, badly coded, which output a "stack trace". Fooey. The only thing the developer is really interested in is what caused the error. What's the purpose of seeing an "error stack", when all the non-root errors are simply errors derived from the root error? You fix the root problem, and the other errors disappear, unless of course, they are show stoppers as well.
    The error stack is actually quite usefull... especially when you want to hide details into a class/function. Look at Oracle for an example, they have the best error messages in their library I ever found. The error returned to you has everything to do with what you're doing. The root error could be something else and when you follow the path you quickly link your context specific message with the actual cause of the problem.

    ...

    Then again... nothing personnal... just my 2 cents... I'm not pushing on anybody to do it... but it works for me.
    Jean-Marc (aka Myrdhrin)
    M2i3 - blog - Remind-M

  20. #20
    SitePoint Zealot
    Join Date
    Jul 2004
    Location
    Brazil,Maringá-PR
    Posts
    128
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by lastcraft
    You should be trying to prevent errors, not logging them, filing them, cataloguing them, filtering them, redirecting them, intercepting them, piping them, queuing them or stacking them.
    Prevent is just part of process. But since nobody is perfect, in special the final user, logging is still part of an endless debugging process. So, if you have a powerfull error logging, easier is to find and fix the errors. What a site has as advantage over the plataform software is that you can see the errors that happens and fix than as soon as possible. Isn't that cool!? Why ignore it?

    Quote Originally Posted by myrdhrin
    I think we'd need to clarify terminology so we can talk using a comon terminology.
    Exactly !!!
    This thread is all about this!
    Basically we have:
    a) unrecover errors.
    Those are errors that we only can say sorry to the user!
    b) user input errors.
    The data that come from the user is invalid
    c) any else?

    but....Why not talk in PHP? let's post examples!

  21. #21
    SitePoint Addict myrdhrin's Avatar
    Join Date
    Jul 2004
    Location
    Montreal
    Posts
    210
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by neves
    Exactly !!!
    This thread is all about this!
    Basically we have:
    a) unrecover errors.
    Those are errors that we only can say sorry to the user!
    b) user input errors.
    The data that come from the user is invalid
    c) any else?
    Here are the kind of error/exception/situations I have seen in my life as an application developer.

    a) unrecoverable errors
    - Install mis-configuration (database, path, function def, etc.)
    - Late binding problems
    - Missing config/code/template files
    - Unexpected problems (server crash, database crash, etc.)

    b) user input errors
    - that could be a very very lengthy list....

    c) can recover errors
    - files that don't have the right attributes when overwriting/deleting/updating a file
    - offline database
    - too busy services (either database, or any kind of service)
    - disconnection from remote server (for any kind of service)
    - file lock/record lock/ {choose a word} lock

    d) compile/linking problem
    - self explanatory...


    Did I miss any?? (I'm sure I did... I'm just asking to be nice :_ )
    Jean-Marc (aka Myrdhrin)
    M2i3 - blog - Remind-M

  22. #22
    SitePoint Zealot
    Join Date
    Jul 2004
    Location
    Brazil,Maringá-PR
    Posts
    128
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by lastcraft
    Pouring over error logs is a spectacularily inefficient way to write code. The time you invest in this could be spent in unit testing, code review or a complete rewrite. The result will be less code and a more elegant solution.
    You are completely right, I can't imagine my self writing code without the security that a Unit Test gives to me
    But I still think that logging errors is good to track new bugs
    Again I remember that this discussion is not about logging errors, but handling situations!

    Quote Originally Posted by myrdhrin
    Here are the kind of error/exception/situations I have seen in my life as an application developer.

    a) unrecoverable errors
    - Install mis-configuration (database, path, function def, etc.)
    - Late binding problems
    - Missing config/code/template files
    - Unexpected problems (server crash, database crash, etc.)

    b) user input errors
    - that could be a very very lengthy list....

    c) can recover errors
    - files that don't have the right attributes when overwriting/deleting/updating a file
    - offline database
    - too busy services (either database, or any kind of service)
    - disconnection from remote server (for any kind of service)
    - file lock/record lock/ {choose a word} lock

    d) compile/linking problem
    - self explanatory...


    Did I miss any?? (I'm sure I did... I'm just asking to be nice :_ )
    Excellent start, myrdhrin
    Since the error types 'a' and 'd' can't be treated or handled respectively, let's focus on b and c errors.
    Does some body could put some examples using the class of the first post?

  23. #23
    eschew sesquipedalians silver trophy sweatje's Avatar
    Join Date
    Jun 2003
    Location
    Iowa, USA
    Posts
    3,749
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    b is not really an error, just a condition that you want to alert the user regarding. In similar cases, I have created a $_SESSION based stack managed by a UserNotifyStack class that I can pile messages into and have them retrieved, displayed and cleared at a later point.

  24. #24
    Non-Member
    Join Date
    Jan 2004
    Location
    Planet Earth
    Posts
    1,764
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As Marcus mentioned, time is better spent making the code work than worrying about future errors if any.


    If there are any errors as far as I'm concerned, they're more than likely to related to missing files of one sort or another

    I may not be using Unit Testing at the moment, but I still go way out my way to be sure that there isn't even a NOTICE in my scripts


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •