2

So I am working with an API, and I wanted to know some good practices of handling errors without breaking the script. Throw anything at me, expose me to more so I can research it further.

Also, examples appreciated, it helps me visually link something to a term/phrase.

Some of my reads:

Error handling in PHP

Community
  • 1
  • 1
Strawberry
  • 66,024
  • 56
  • 149
  • 197

3 Answers3

2
  1. Log errors
  2. If this is a user facing application/page show them a human friendly error message and not the error message returned by the API
  3. Exceptions should be used if your API call fails for technical reasons (i.e. curl fails to connect) or if the API is experiencing technical issues that are out of the ordinary. Otherwise normal error handling should be used (i.e. the user provided invalid data)
John Conde
  • 217,595
  • 99
  • 455
  • 496
2

Error Handling, is a big big topic. It cannot be narrowed down to a single answer. Best practices are generally judge on the basis of how user friendly and secured they are. So basically your api, should have multiple feature for error alone.

  • Should include a way to log the errors and display if user requires it.
  • Number your errors. Give every error an unique number to identify it.
  • Bring exceptions into practice. Not every errors are ACTUAL, some are exceptions.
  • Multiple ways to handle the error have to be created. Liking grouping the errors at once or showing each one by one.
Starx
  • 77,474
  • 47
  • 185
  • 261
1

Usually what I do is wrap potential problematic code - such as database connections - with try/catch blocks. Then if any errors are caught, put human readable equivalants in a global array so you can safely output the list to the template.

For instance:

<?php
$errors = array();
try
{
   if (!$var)
        throw new Exception('Meh..');
}
catch (Exception $e)
{
    // Use $e with caution, as with database connection it can sometimes contain your password. :P
    $errors[] = 'Something is seriously wrong with that last statement.<br />' . $e;
}


// Template layers..

echo '
        <ul>';
foreach ($errors as $error)
    echo '
            <li>', $error, '</li>';

echo '
        </ul>';
Scotty C.
  • 744
  • 4
  • 16