HiveBrain v1.2.0
Get Started
← Back to all entries
debugphpMinor

Custom error/fatal error and exception handler in PHP

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
errorexceptionphpfatalcustomandhandler

Problem

Introduction

I wrote three functions that aims to log errors and exceptions as well as show a user a generic error page. Would appreciate some feedback on it with regards to the PSR standards and if I have left out anything of value.

Memory issue:

I am aware that the memory issue has not been addressed in this code, i.e. if you run out of memory the errors will not be logged. However, this isn't an issue I'm looking to solve at the moment.

Code:

__toString() . PHP_EOL, FILE_APPEND);
    // Sets header and redirect user to generic error page
    header('HTTP/1.1 500 Internal Server Error', true, 500);
    require_once('500.php');
    // Terminates the script
    exit;
  }

  // Logs on shutdown caused by an error
  function fatalErrorHandler() {
    // Gets the last occured error
    $error = error_get_last();
    // Check if error exists
    if (!empty($error) && in_array($error['type'], array(E_ERROR, E_USER_ERROR))) {
      // Sets path to error log
      $fatalErrorLog = "/home/ubuntu/errors.log";
      // Generic fatal error structure
      $fatal = 'FATAL  ' . $error['message'] . ' in ' . $error['file'] . ' on line ' . $error['line'];
      // Logs fatal error to file
      file_put_contents($fatalErrorLog, $fatal . PHP_EOL, FILE_APPEND);
      // Sets header and redirect user to generic error page
      header('HTTP/1.1 500 Internal Server Error', true, 500);
      require_once('500.php');
      // Terminates the script
      exit;
    }
  }

  // Sets custom handler for errors, exceptions and fatal errors
  set_error_handler('errorHandler');
  set_exception_handler('exceptionHandler');
  register_shutdown_function('fatalErrorHandler');
?>

Solution

The first thing which comes to my mind when reading your code is how concurrent requests with errors can tamper with the written data. You can aqquire an exclusive lock on the file for the duration of the writing with the flag LOCK_EX (see file_put_contents documentation).

I would also make sure the file 500.php actually exists. You could also avoid using require_once since the script is terminated afterwards and the possibility for another include is non-existent.

I assume the comments are because the code is posted here, since none of them provide extra information your code doesn't provide. Otherwise I think your code look fine. The variables have meaningful names and the indentation is good.

Happy coding!

Context

StackExchange Code Review Q#103954, answer score: 2

Revisions (0)

No revisions yet.