0

I have been dealing with PHP since 2000, but not very actively, and my knowledge of PHP5 is quite horrible. Recently I got my interest for webdevelopment back after a 5 year long break, and I started working on a project. I wrote a class for that project that became fairly large, but so far without any specific error handling.

The purpose of the class is to parse HTML files with a specific layout and handle its data, and it was more or less a training exercise for me to get back into the game. I started to rewrite the class now, and I decided it was time to be a little more professional about error handling than simply using die(), which I have been using a lot so far. I think we can all agree that is a terrible direction to take. I want the class to be quite project independent, so that I can distribute it to whoever wants to use it.

The HTML files I want to parse contain tables with specific bordercolors, trs with specific bgcolors, but the number of elements are dynamic. To validate that the HTML files actually have this specific pattern, I have the following sample (pseudo)code

public function Validate() {

    $tables = getall('table', $this->data);

    foreach ($tables as $table) {
        if ($table->bordercolor != 'navy' && $table->cellspacing != 0) {
            // Error
        }

        foreach ($tables->tr as $tr) {
            if ($tr->bgcolor != '#fff') {
                // Error
            }
        }
    }
    return true;
}

Where it says // Error, the HTML layout doesn't check out and my class should not attempt to parse it. Traditionally I would do this:

if ($table->bgcolor != '#fff') {
    $this->error = 'Invalid HTML layout';
    return false;
}

And from where I call the method I would use

if ($class->Validate() === false) {
    exit_with_error($class->GetError()); // Simple return of $this->error
}

I've always thought it's a decent approach because of it's simplicity. However that's also a disadvantage as it doesn't really provide any in-depth information of the error apart from the text itself. I can't see where the error was triggered, what methods were called, etc.

Since I resumed my PHP hobby I have discovered exceptions. My problem with them is simply that I don't understand how to properly use them. And if I should use them at all. I would like my class to be portable; can I use exceptions to handle errors at all? And if yes, how can I communicate the errors (i.e. translate my traditional error handling)? Or perhaps there is an even better approach to take, which I don't know about.

Any help appreciated :)

4

2 に答える 2

0

実行方法に問題はありませんが、例外について詳しく知りたい場合は、try/catchステートメントの使用方法を学習してください。通常、次のようになります。

try {
  //some code that may cause an error here
} catch (Exception e) {
  //if a error is found, or an exception is thrown in the try statement, whatever here will execute
  //you can get the error message by using e->getMessage()
}

あなたはここでそれについてもっと読むことができます:http://php.net/manual/en/language.exceptions.php

于 2012-11-29T01:48:39.917 に答える
0

You are certainly thinking along the right path. Typically, I like to separatte class design from error handling logic. In other words I don't want to have a bunch of $this->error = 'something' logic in the class, as why would you want to add extra code to every class to store/handle/report errors.

Now you get into exceptions vs. errors and when to use each. This is likely a subject for debate, but my personal preference has largely been to throw Exceptions in cases where you get to a point in your code that you cannot recover from or do not have the logic to handle. A great example of this, that I typically use, is throwing Exceptions right at the beginning of any class method that requires parameters of a certain sort or value. Like this example:

public method set_attribute($value) {
   if (empty($value)) {
      throw new Exception('You must send me something');
   } else if (!is_string($value)) {
      throw new Exception("You sent me something but it wasn't the string I was expecting.");
   }
   // method logic here
}

Here if the caller didn't give us a non-empty string, we throw an Exception, as we were not expecting this and we can't guarantee successful completion of the method without a proper value. There is not reason to continue with the method at all. We send the caller the exception with a message about the problem. Hopefully they invoked this method in a try-catch block and can gracefully handle the exception and pass it along up the call stack. If not, your code just stopped execution with fatal error from an uncaught exception (something really easy to catch in testing).

Triggering errors, I honestly use a lot less, and typically use them more for debug, warning purposes. An example of this might be a deprecated method that you still want to work, but you want to give the user an error on

public function old_method() {
   trigger_error('This method had been deprecated. You should consider not using it anymore.'. E_USER_WARNING);
   // method logic
}

Of course you can trigger whatever level of E_USER class warning here yourself.

Like I said, I tend to work a lot more with Exceptions, as they are also easily extensible for easy use with logging and such. I almost always would have a custom Exception class extending from PHP's base Exception class that also provides logging, etc.

The other thing to consider is global error handling and Exceptoin handling. I strongly recommend using these and having these be some of the very first lines of code in any new project. Again, it will give you much better control over how you log errors/exceptions than what you can get by default.

于 2012-11-29T01:58:00.140 に答える