+ All Categories
Home > Documents > [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

[Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

Date post: 14-Apr-2018
Category:
Upload: seher-kurtay
View: 227 times
Download: 0 times
Share this document with a friend

of 26

Transcript
  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    1/26

    By icarus

    This article copyright Melonfire 20002002. All rights reserved.

    http://www.melonfire.com/
  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    2/26

    Table of ContentsExpect The Unexpected......................................................................................................................................1

    Back To Class......................................................................................................................................................2

    The Bare Bones...................................................................................................................................................4

    How Things Work...............................................................................................................................................9

    The Number Game...........................................................................................................................................11

    Running On Empty...........................................................................................................................................14

    Raising An Alarm.............................................................................................................................................16

    A WellFormed Idea........................................................................................................................................20

    Going To The Source........................................................................................................................................24

    Building A Generic Error Reporting Class In PHP

    i

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    3/26

    Expect The Unexpected

    One of the most fundamental tasks during the development cycle for a software application involves writing

    code to trap and gracefully recover from exceptions.

    This might seem pretty obvious, but the reality as anyone who's ever spent time developing a robust Webapplication will tell you is completely different. Most developers, especially those new to the Web

    paradigm, treat error handling like an unwanted stepchild, preferring instead to concentrate their efforts on

    implementing and delivering the application against aggressive deadlines. Error handling is usually an

    afterthought...if it's thought of at all.

    This is a shame, because most programming languages including PHP, which is the subject of this article

    come with a fullfeatured error handling API, which provides you with a number of options when it comes to

    trapping and resolving errors. Making use of such an errorhandling API in a consistent manner throughout

    the scripts that power your application bears rich dividends: your code is more robust, application test time is

    shorter (since most errors have been thought through and handled in your code), and users never get the

    opportunity to see ugly, incomprehensible debug messages generated from the language's internals.

    Even if you develop and release a Web application without building in any errorhandling routines (either

    through ignorance or laziness), you can be sure that your customer's going to demand a fix for it in the next

    release of the software. And since it's one of the few things you're likely to do over and over again when

    building Web applications, it's worthwhile spending a little time to make the process as painless as possible.

    That's where this article comes in. Over the next few pages, I'll be attempting to build a reusable library of

    functions that allow you to handle script errors in a generic manner, in an attempt to save myself (and,

    hopefully, you) some time when the next project comes around. The end result of this experiment will be a

    PHP class that can be easily included in your scripts, and that provides a simple way to trap and display errors

    consistently. I should warn you at the outset that it may not in fact, probably will not meet *all* yourneeds; however, the process should be instructive, especially if you're new to object programming in PHP, and

    you'll have very little difficulty customizing it to your own requirements.

    Let's get going!

    Expect The Unexpected 1

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    4/26

    Back To Class

    Before we begin, let's just go over the basics quickly:

    In PHP, a "class" is simply a set of program statements which perform a specific task. A typical class

    definition contains both variables and functions, and serves as the template from which to spawn specificinstances of that class.

    Once a class has been defined, PHP allows you to spawn as many instances of the class as you like. These

    instances of a class are referred to as "objects". Each of these instances is a completely independent object,

    with its own properties and methods, and can thus be manipulated independently of other objects.

    This comes in handy in situations where you need to spawn more than one instance of an object for

    example, two simultaneous database links for two simultaneous queries, or two shopping carts. Classes also

    help you to separate your code into independent modules, and thereby simplify code maintenance and

    changes.

    A class definition typically looks like this:

    Once the class has been defined, an object can be spawned with the "new" keyword and assigned to a PHP

    variable,

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    5/26

    $myCart = new ShoppingCart;

    ?>

    which can then be used to access all object methods and properties.

    Building A Generic Error Reporting Class In PHP

    Back To Class 3

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    6/26

    The Bare Bones

    So that's the theory. Let's now spend a few minutes discussing the rationale behind the errorReporter object I

    plan to build.

    Consider the following script, which is representative of the way many PHP applications are coded:

    Welcome!

    Pick a store:

    Men

    Women

    Children

    The Bare Bones 4

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    7/26

    We're having a special Thanksgiving sale, with up to

    60% off on selected items. Come on in and check it out!

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    8/26

    Visit our sponsor:

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    9/26

    As you can see, this script dynamically builds an HTML page, using PHP to generate some components of the

    data that appears on the page. The PHP business logic is closely intertwined with the HTML interface code,

    and is executed sequentially, line by line, as the PHP engine parses the document.

    Now, consider what happens if an error occurs during execution of the PHP functions near the middle of the

    script say, for example, the database server does down. Here's what the resulting output might look like:

    Ugly, huh?

    Obviously, if you're in the business of building professional Web applications, an incomplete page like the

    one above opens the door to a minefield of problems possible further errors if the user attempts to invoke a

    command on the incomplete page, support calls if the error message is particularly difficult to understand (or

    absent), and so on. Therefore, it makes sense to ensure that such errors, if they occur, are handled in a graceful

    manner, with a consistent error screen displayed to the user and no potential to further compound the mistake.

    Further, it is possible to classify the errors that occur within an application into two basic categories: serious

    ("fatal") errors that require the script to terminate immediately, such as a broken database connection or a file

    I/O error, and less serious ("nonfatal") errors that do not require the script to terminate immediately, such as

    missing or incorrectlytyped form data.

    Keeping this in mind, it's possible to create a simple class that handles error reporting gracefully, producing

    consistent error messages so that users are protected from the situation described a few pages back. This

    errorReporter class would consist of the following three components:

    Methods that allows the developer to raise, or trigger, errors whenever required, and to add these

    errors to an "error stack". This error stack is merely a PHP structure (here, an associative array) that

    holds a list of all the errors (both fatal and nonfatal) encountered.

    1.

    Methods that may be called by the developer to clear the screen of previouslygenerated data and2.

    Building A Generic Error Reporting Class In PHP

    The Bare Bones 7

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    10/26

    redraw it with an error message (this is necessary to avoid the display of incomplete pages, such as

    the one above). Fatal errors are reported immediately; reporting of nonfatal errors may be controlled

    by the developer.

    Utility methods to manipulate the error stack.3.

    As you will see, these three basic components make it possible to build a very simple (and yet very useful)

    errorReporter object.

    Building A Generic Error Reporting Class In PHP

    The Bare Bones 8

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    11/26

    How Things Work

    Now, before proceeding further, I need to decide how this class is going to work. Here's how I plan to use it:

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    12/26

    // check for missing form variables

    // errors in this section would be considered nonfatal

    if (!$sku) { $e>raiseError(1101, "SKU"); }

    if (!$price) { $e>raiseError(1101, "PRICE"); }

    // display nonfatal errors (if any)

    if ($e>numErrors() > 0)

    {

    $e>displayNonFatalErrors();

    }

    // if we get this far, it means the script encountered

    // zero fatals and zero nonfatals

    // in other words, the script was successfully executed

    // display success page

    include("success.tmpl");

    ?>

    As you can see, I would like to wrap each function call in my script with a call to the errorReporter class. If a

    function call fails, an error will be generated via a unique error code and added to the error stack. If the error

    is evaluated as fatal, an appropriate error message will be immediately displayed to the user; if the error is

    evaluated as nonfatal, script processing will continue and the developer has the option to throw up an error

    screen at a later date containing a list of nonfatal errors.

    Once the basic functionality of the class is clear, it's a good idea to spend some time listing the important

    methods, together with their purpose. Here's my initial cut:

    raiseError($code, $data) raise an error using a predefined error code and optional debug data;

    numErrors() check the number of errors currently held in the error stack;

    displayFatalError($code, $data) display the fatal error screen;

    displayNonFatalErrors() display the nonfatal error screen;

    flushErrors() reset the error stack.

    These are the essential methods; there may be more, which I will add as development progresses.

    Building A Generic Error Reporting Class In PHP

    How Things Work 10

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    13/26

    The Number Game

    Right. So I now know how the class is supposed to work, plus I have a fairly good idea of what the methods

    encapsulated within it will look like. This is a good time to start writing some code.

    You might find it helpful to download the complete class code at this point, so that you can refer to it over thenext few pages.

    errorReporter.zip

    Let's begin by setting up the class definition:

    // errorReporter.class.php

    // class to capture and display errors in a consistent manner

    class errorReporter{

    // snip

    }

    Now, since I plan to build some basic errorhandling routines into this class, I need to add a variable to hold

    this information.

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    14/26

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    15/26

    102 => "Could not connect to database server",

    103 => "Database already exists",

    104 => "Could not select database",

    201 => "Could not create directory",

    202 => "Could not copy file(s)",

    203 => "Could not execute command",

    204 => "Could not read configuration file",

    205 => "Could not delete file(s)",

    206 => "Could not read file(s)",

    207 => "Could not write file(s)",

    208 => "Could not open file(s)",

    209 => "File already exists",

    210 => "Could not delete directory",

    301 => "Session expired",

    401 => "An internal script error occurred",

    1101 => "Required field empty",

    1102 => "Invalid data in field",

    1103 => "File upload unsuccessful",

    1201 => "Missing record identifier(s)"

    );

    // snip

    }

    This predefined list of error codes and messages covers the most common errors developers experience

    when building Web applications. Since this list is defined once, and indexed by a unique numeric code, it may

    be reused over and over, in different scripts, to display consistent error messages. And in the event that a

    particular error message is deemed confusing or difficult to understand, all you need to do is update this

    master list, and the change will be immediately reflected across all error screens thrown up by the application.

    Building A Generic Error Reporting Class In PHP

    The Number Game 13

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    16/26

    Running On Empty

    Let's now begin constructing the class methods. I'll start with the constructor:

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    17/26

    Once a buffer has been defined, the script proceeds to execute as usual. When you've decided that it's time to

    display the contents of the buffer to the user, you can simultaneously end output buffering and send the

    contents of the current buffer to the browser. Alternative, you can also clear the contents of this buffer at any

    time via a call to ob_clean() (as you will see on the next page, this is the function I will be using to clear and

    redraw the screen when an error occurs).

    Building A Generic Error Reporting Class In PHP

    Running On Empty 15

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    18/26

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    19/26

    }

    // snip

    }

    If an error is fatal, the displayFatalError() method is invoked. Here's what it looks like:

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    20/26

    The error template to be displayed here is contained within a separate file, named "errorfatal.php", and

    include()d where needed by displayFatalError(). This template can be customized to your specific

    requirements here's my barebones version:

    Error!

    The following fatal error occurred:

    (error code )


    ()

    Wanna see how it works? Here's an example of how you could use the errorReporter in a script to trap fatal

    errors,

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    21/26

    // write to file

    $filename = "data.txt";

    $fd = fopen ($filename, "wb") or $e>raiseError(208,

    $filename); $ret =

    fwrite ($fd, "aloha!") or $e>raiseError(207, $filename);

    fclose ($fd);

    // zero errors?

    // display success code

    echo "Success!";

    ?>

    and here's an example of the error screen displayed if an error occurs during script execution:

    Note the manner in which the output generated by the script above is first cleared from the output buffer by

    the errorReporter class, and is then completely replaced with the template containing an appropriate error

    message. No more mangled screens, no more confused users!

    Building A Generic Error Reporting Class In PHP

    Raising An Alarm 19

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    22/26

    A WellFormed Idea

    Unlike fatal errors, which immediately cause script termination when they are raised, nonfatal errors merely

    get registered in the error stack the developer is free to display these nonfatal errors at any time (or even

    ignore them altogether).

    Here's what the displayNonFatalErrors() method looks like:

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    23/26

    Here's what my nonfatal error template looks like:

    Error!

    The following nonfatal errors occurred:

    ()

    ()

    Pretty simple, this this script accepts the $errorList array created by the displayNonFatalErrors() method

    and iterates through it to create a bulleted list of errors.

    It should be noted that I added this type of error primarily to handle form validation tasks if you have a large

    or complex form to validate, it's inconvenient to terminate script processing every time a validation routine

    fails (as would happen if I only used fatal errors). Nonfatal errors make it possible to perform a series of

    validation routines on form data, store the errors that occur in an array, and then display all the errors at one

    time for the user to view and correct.

    Building A Generic Error Reporting Class In PHP

    A WellFormed Idea 21

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    24/26

    Here's an example of how you could use the errorReporter's nonfatal errors while performing form

    validation:

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    25/26

    if (empty($_POST['flavour']))

    {

    $e>raiseError(1101, "FLAVOUR");

    }

    // check to see if any errors

    // display if so

    if ($e>numErrors() > 0)

    {

    $e>displayNonFatalErrors();

    }

    // if we get this far, it means

    // there were no errors in the form data

    // now let's insert this data into a database

    $name = $_POST['name'];

    $filling = $_POST['filling'];

    $flavour = $_POST['flavour'];

    $connection = mysql_connect("localhost", "user", "pass") or

    $e>raiseError(102, "LOCALHOST");

    mysql_select_db("users") or $e>raiseError(104, "USERS");

    $query =

    "INSERT INTO profile (name, filling, flavour) VALUES ('$name',

    '$filling', '$flavour')"; $result = mysql_query($query) or

    $e>raiseError(101, $query . mysql_error());

    // all done?// display success code

    echo "Success!";

    }

    ?>

    And here's an example of the error screen you might see:

    Building A Generic Error Reporting Class In PHP

    A WellFormed Idea 23

  • 7/30/2019 [Developer Shed Network] Server Side - PHP - Building a Generic Error Reporting Class in PHP

    26/26

    Going To The Source

    Of course, this is just my first stab at a generic error reporting class. It's designed for very simple

    requirements, and may be way too primitive for your needs. If this is the case, you have two basic options:

    File the results of my efforts in the trash can and write your own, muchcooler,doeseverythingbutmaketoast class;

    1.

    Pick up a free, opensource PHP class which offers a more powerful feature set.2.

    If you picked door one, you don't really need my help any more. You can stop reading right now and get to

    work. Have fun, and remember to send me a Christmas card if you sell your software for a million bucks.

    If, on the other hand, you're lazy and figured that door two was more promising, you'll be happy to hear that

    the Web has a huge number of powerful error handling classes floating around it, many of them extremely

    powerful. Here are two that looked particularly interesting:

    Gyozo Papp's ErrorHandler class, at http://gremlins.mirrors.phpclasses.org/browse.html/package/345.html

    Lennart Groetzbach's debugHelper class, at

    http://gremlins.mirrors.phpclasses.org/browse.html/package/891.html

    You can also read more about the material discussed in this article, at the following links:

    PHP output control functions, at http://www.php.net/manual/en/ref.outcontrol.php

    PHP error handling functions, at http://www.php.net/manual/en/ref.errorfunc.php

    Classes in PHP, at http://www.php.net/manual/en/language.oop.php

    And that's about all for the moment. In this article, you expanded your knowledge of PHP's OOP capabilities

    by actually using all that theory to build something useful an error reporting widget which can be wrapped

    around your PHP scripts to provide consistent and reusable error messages without breaking your Web pages.

    If you're a stressedout Web developer working on a Web site or application, you might find this object a

    handy tool in your next development effort. If you're a novice programmer struggling to understand how OOP

    can make your life easier, I hope this article offered some pointers, as well as some illustration of how

    objectoriented programming works. And if you don't fit into either of those categories well, I hope you

    found it interesting and informative, anyway.

    See you soon!

    Note: All examples in this article have been tested on Linux/i586 with PHP 4.2.3. Examples are illustrative

    only, and are not meant for a production environment. Melonfire provides no warranties or support for the

    source code described in this article. YMMV!

    http://gremlins.mirrors.phpclasses.org/browse.html/package/345.htmlhttp://gremlins.mirrors.phpclasses.org/browse.html/package/891.htmlhttp://gremlins.mirrors.phpclasses.org/browse.html/package/891.htmlhttp://www.php.net/manual/en/language.oop.phphttp://www.php.net/manual/en/ref.errorfunc.phphttp://www.php.net/manual/en/ref.outcontrol.phphttp://gremlins.mirrors.phpclasses.org/browse.html/package/891.htmlhttp://gremlins.mirrors.phpclasses.org/browse.html/package/345.html

Recommended