Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard PHP error function with __LINE__ __FILE__etc?

so, instead of lots of instances of

if (odbc_exec($sql))
{
}
else
{
  myErrorHandlingFunction();
}

I wrap that in a function

function myOdbxExec($sql)
{
  if (odbc_exec($sql))
  {
  }
  else
  {
    myErrorHandlingFunction();
  }
}

BUT I would like myErrorHandlingFunction() to report things like __LINE__ __FILE__ etc

Which looks like I have to pass thoses infos to every call of helper functions, e.g. myOdbxExec($sql, __FILE__, __LINE__) which makes my code look messy.

function myErrorHandlingFunction($errorTExt, $fiel, $line)
{
  // error reporting code goes here
}


function myOdbxExec($sql, $file, $line)
{
  if (odbc_exec($sql))
  {
  }
  else
  {
    myErrorHandlingFunction();
  }
}

$sql = 'select * from ... blah, blah, blah...';
myOdbxExec($sql, __FILE__, __LINE__);   // <==== this is *ugly*

In C I would hide it all behind a #define, e.g. #define MY_OFBC_EXEC(sql) myOdbxExec(sql, __FILE__, __LINE__)

1) (how) can I do that in PHP 2) what else is worth outoputting? e.g. error_get_last()? but that has no meaning if odbc_exec() fails ...

To rephrase the question - what's the generic approach to PHP error handling? (especially when set_error_handler() doesn't really apply?


Edit: just to be clear - I do want to handle exceptions, programming errors, etc, but, as my example shows, I also want to handle soemthings the teh PHP interpreter might noit consider to be an error, like odbc_exec() returning false().

like image 910
Mawg says reinstate Monica Avatar asked Dec 09 '22 14:12

Mawg says reinstate Monica


1 Answers

Both the above answers mentioning debug_backtrace are answering your _______LINE_____ / _______FILE___ question with the debug_backtrace() function. I've wanted this answer too in the past, so have put together a quick function to handle it.

function myErrorHandlingFunction($message, $type=E_USER_NOTICE) {
    $backtrace = debug_backtrace();
    foreach($backtrace as $entry) {
        if ($entry['function'] == __FUNCTION__) {
            trigger_error($entry['file'] . '#' . $entry['line'] . ' ' . $message, $type);
            return true;
        }
    }
    return false;
}

You can then call, for instance, myErrorHandlingFunction('my error message');

or myErrorHandlingFunction('my fatal error message', E_USER_ERROR);

or try { ... } catch (Exception $e) { myErrorHandlingFunction($e->getMessage()); }

like image 181
Colin Avatar answered Dec 25 '22 12:12

Colin