2

I am working on a very old legacy project and somewhere in a script runned by cron, something happens that stops the script and an advisory lock is left on a file, that causes further problems in the next rounds of scripts runned later by cron. Based on logs more or less I pinpointed which part of the script fails, so I wrapped that in a try-finally block. However I am quite sure about that that's the part which fails, the file in question continues to stuck locked, so I suspect that some kind of error happens like E_ERROR that is not catchable like an \Exception. I would like to write a custom error handler with set_error_handler and I have to define error types to handle an I only want to handle errors that halt the execution of the script, my question is beside the E_ERROR, which error types interrupt executions as well?

set_error_handler('fatalErrorHandler', [E_ERROR]);

function fatalErrorHandler($errno, $errstr, $errfile, $errline){
     throw new \Exception($errstr." @$errfile:$errline", $errno);
}

/* ... */ 

try{
     // Likely defective code...
}catch(\Exception $e) {
     $cronlocklog->add("cron job failed with error: ".$e->getMessage());
} finally {
     flock($cronlockfd, LOCK_UN);
}
5
  • Why don't you check error log to find out exactly what's going on? Then you'd better fix that because even though custom error handler is called on fatal errors, you cannot prevent halting the script. Fatal means there's no way to continue though you have the chance to do some things before execution stops.
    – marekful
    May 14, 2018 at 12:46
  • 1
    @marekful I think OP wants the script to stop after error, but wants the script to release lock too after error
    – Med
    May 14, 2018 at 12:47
  • I just want to note that in >PHP7, when a E_ERROR or E_RECOVERABLE_ERROR occurs, a special subtype of Exception is thrown (Error). Assuming you are using an older version of php, E_RECOVERABLE_ERROR will turn into a E_ERROR if you have not set up something to handle it with the set_error_handler function. Only E_ERROR will halt execution (With few exceptions). php.net/manual/en/errorfunc.constants.php . Consider that some errors cannot be recovered from or caught using Error (i.e. if you run out of memory) and will always halt execution.
    – ZombieTfk
    May 14, 2018 at 12:49
  • Instead of exception handling I would recommend looking into why the lock is implemented and whether or not the code actually needs it. It sounds like it was over-zealously implemented if it's causing this many issues.
    – MonkeyZeus
    May 14, 2018 at 12:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.