6

I'm looking for a general way to handle session_start errors, not a way to handle one specific error. There are numerous errors which can happen, such as the session directory being full, which cause a fatal error. I want a way to trap those errors and handle them cleanly, without having to write custom handlers for each possibility.

Something like this (but not this as it doesn't work):

try{
    session_start();
}catch(Exception  $e){
    echo $e->getMessage();
}

All help appreciated, thanks in advance.

user2320402
  • 379
  • 5
  • 8
  • Look up [set_error_handler](http://php.net/manual/en/function.set-error-handler.php) – Anigel May 15 '13 at 14:53
  • See also [this answer](http://stackoverflow.com/questions/10331084/error-logging-in-a-smooth-way/10476589#10476589) on error handling in general. – Ja͢ck May 15 '13 at 14:56

1 Answers1

5

The regular PHP session functions don't throw exceptions but trigger errors. Try writing an error handler function and setting the error handler before calling session_start.

function session_error_handling_function($code, $msg, $file, $line) {
    // your handling code here
}

set_error_handler('session_error_handling_function');
session_start();
restore_error_handler();

However, this is just for capturing the session errors. A better way would be to create a general error handler that creates exceptions from errors and surround code parts that may throw errors with try ... catch blocks.

chiborg
  • 26,978
  • 14
  • 97
  • 115