exception snippets

PHP exception and error handling with register_shutdown_function and set_exception_handler

Tagged blank, page, php, exception, 500  Languages php

PHP has the crappiest error handling I've ever seen. The default behavior is to show all error messages to the user. If you disable this then you get a blank screen instead. The trick is to register an error handler with register_shutdown_function, which is then called if for example memory is exhausted. You could perhaps also use an ErrorDocument 500, but that didn't work for me.

Here's the code I've used to handle both application exceptions and errors, such as memory limit exceeded. The trick is to have a global variable that indicates whether the script was run successfully or not. Add your code here: "Insert your buggy code here".

$no_errors_detected = false;

class DispatchErrors 
{
    static function handleException($exception) 
    {
      Logging::error($message);

        header( 'Location: /error500.html' );
    }
    
    static function handleShutdown()
    {
        global $no_errors_detected;
        
        if (!$no_errors_detected)
        {
            header( 'Location: /error500.html' );
        }       
    }
}

register_shutdown_function(array('DispatchErrors', 'handleShutdown'));
set_exception_handler(array('DispatchErrors', 'handleException'));

# handleShutdown will be called
#range(0, 10000000000000000000);

# handleException will be called
#throw new Exception("abcd");

# Insert your buggy code here

$no_errors_detected = true;

How to create a catch-all exception handler for Rails

Tagged rescue_locally, exception, rescue_in_public, rails  Languages ruby

Rails' exception handling is defined in this file /usr/local/lib/ruby/gems/1.8/gems/actionpack-2.3.2/lib/action_controller/rescue.rb. To intercept all errors in your Rails app, you can do this:

module GulagNotifier
  def self.included(base)
    if base.instance_methods.include?("rescue_action_in_public")
      base.module_eval { alias_method_chain :rescue_action_in_public, :gulag }
    end
    if base.instance_methods.include?("rescue_action_locally")
      base.module_eval { alias_method_chain :rescue_action_locally, :gulag }
    end
  end

  def rescue_action_locally_with_gulag(exception)
    send_to_gulag(exception)
    rescue_action_locally_without_gulag(exception)
  end

  def rescue_action_in_public_with_gulag(exception)
    send_to_gulag(exception)
    rescue_action_in_public_without_gulag(exception)
  end 

  def send_to_gulag(exception)
# Do whatever you want with the exception
  end
  
end