Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is error checking too much?

During the process of my PHP learning I have been trying to read up on the best practices for error reporting and handling, but statements vary person to person and I have struggled to come up with a clear concise way of handling errors in my applications. I use exceptions on things that could go wrong, but for the most part it is hard for me to understand whether an exception should kill the application and display an error page or just be caught and silently dealt with.

Something that seems to elude me is, is there such thing as too much reporting? Every single time you call a function something could go horribly wrong meaning that if you were to confirm every single function call you would have to fill pages with if statements and work out what effect one failure may have on the rest. Is there a concise document or idea for error reporting that could clear this up for me? Are there best practices? What are the best examples of good error handling?

Currently I do the following:

  • Add important event results to an array to be logged and emailed to me if a fatal error was to occur
  • Display abstract/generic errors for fatal errors.
  • Use exceptions for cases that are likely to fail
  • Turn on error reporting in a development environment and off for live environment
  • Validate all user input data
  • Sanitizing invalid user input
  • Display concise, informative error messages to users without providing a platform for exploitation.
like image 252
Sam Avatar asked Oct 22 '22 19:10

Sam


1 Answers

Exceptions are the only thing that you haven't understood IMHO: exceptions are meant to be out of your control, are meant to be caught be dealt with from outside the scope they are thrown in. The try block has a specific limit: it should contain related actions. For example take a database try catch block:

$array = array();
try {
    // connect throws exception on fail
    // query throws exception on fail
    // fetch results into $array
} catch (...) {
    $array[0]['default'] = 'me';
    $array[0]['default2'] = ...;
    ...
}

as you can see I put every database related function inside the try block. If the connection fails the query and the fetching is not performed because they would have no sense without a connection. If the querying fails the fetching is skipped because there would be no sense in fetching no results. And if anything goes wrong, I have an empty $array to deal with: so I can, for example, populate it with default data.

Using exceptions like:

$array = array();
try {
    if (!file_exists('file.php')) throw new Exception('file does not exists');
    include('file.php');
} catch (Exception $e) {
    trigger_error($e->getMessage());
}

makes no sense. It just a longer version of:

if (!file_exists('file.php')) trigger_error('file does not exists');
    include('file.php');
like image 140
Shoe Avatar answered Oct 24 '22 15:10

Shoe