views:

78

answers:

2

I am looking for some coding ideas on the following task I am trying to achive.

I have a list of Error Numbers, Description, and User Friendly Description in a document.

Ex:
Error Number, Description, User Friendly Description 
-----------------------------------------------------
1, Internal Error, "An Internal Error has occurred. Please try again later".
2, Delete Failed, "Unable to delete an Entry. Please try later".

I want to write a PHP class to store all the above in such a fashion that I can access them later with ease when an error occurs in the code..

Ex: If my code received an error 2, I want to check that error code with the list of error codes in the class, retrieve the description, user friendly description and display it to the user.

I want this to be of minimum overhead. So, don't want to store it in database.

I am using PHP5 with Zend MVC framework. Anybody can help me with the best possible sample code?

Thanks

A: 

I like to use a simple custom error handler and custom exception handler that do the following:

If in development mode:

  • Show the detailed error message

  • If E_WARNING or worse, output error message into a log file (e.g. using Zend_Log)

  • If a fatal error, halt execution and show a nice error page with a full backtrace

If in production mode:

  • Only log error messages

  • On fatal errors, halt execution and show a nice "an error has occurred" page only.

I like working with errors, so any exception I catch I call a trigger_error() for to do the output and logging.

You can also extend the default Exception class to do the logging and display. You would want to turn any error that occurs into exceptions. Manual errors you would then trigger as exception using throw.

Inspiration:

Kohana's Error Handler (Screenshot here) is the nicest and greatest I've seen to date. It's open source, maybe you can even grab out that part (make sure you read the license first, though.)

Pekka
+1  A: 
  • Write an ini file with the error code and the user friendly text.
  • write an class which extends Exception which fetches your errorcodes from the ini file. add a method e.g. public function getUserFriendlyMsg(){} which returns the string from the ini file.

in your normal code when you have such an error you just need to throw the exception. e.g.

throw new My_Exception('Delete failed',2);

in your e.g. controller:

try{
    // your code
}catch(My_Exception $e){
    echo $e->getUserFriendlyMsg();
}

Note: you should consider extending your excpetion class to log the failures to a logfile, for this you can introduce servity levels. (see the manual - exception handling)

Rufinus
INI files are not the best choice for me.. It would be better to use a PHP class instead..
Vincent
you can use any kind of data file. you even can use Zend_Translate to build the "userfriendly" error messages in different languages.
Rufinus