0

How can I terminate / halt a PHP script and return an error exit code if ANY errors occur?

Basically the functionality that is provided by set -e in Bash?

I've tried setting ini_set('error_reporting', E_ALL); but this does not actually halt the script when an error occurs.

Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
  • Think you have to distinguish between errors/warnings/notices etc. As for the later - https://stackoverflow.com/questions/10520390/stop-script-execution-upon-notice-warning which is effectively what you have. – Nigel Ren Jul 24 '20 at 16:22

3 Answers3

0

This seems to do the job:

set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});
Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
  • It is still possible to catch an `ErrorException` and handle it inside a `catch` part. – noam Jul 24 '20 at 16:22
0

I think your going to want to control errors and handle them in a particular way.

In which case I would

try{
    // CODE THAT MAY THROW ERROR
    $connection = new Connection('Grandmas_prosthetic_bluetooth_api');
    $connection->getWalkingDistance();
}catch(){
    // ON ERROR HANDLE 
    die('this is error happened because grandma wasn't around...');
    // OR 
    echo json_encode(array(
        'result' => 'failure',
        'message' => 'bro something else bad happened...'
    ));
    exit;
} 

I like this cause if another script is calling this at least it can handle what happens when this script breaks like ajax calls or curls...

Else if your goal is to leave people not knowing anything you can just die() or exit();

If you need information about the error you should enable your error logs and tail them for the information, because in general exposing raw errors to the screen is really not great in practice.

Cengleby
  • 86
  • 5
-1

PHP has it's own function for that: exit(). You can pass your exit code as you need.

noam
  • 538
  • 5
  • 19