Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS 

Adding helpful error messages to your Ruby code

This Ruby code raises an error if the XPath query fails because the attribute being queried did not exist for the given element.

  def map_pattr(node, fieldx, valuex)
    begin
    parameter = node.root.elements["parameter[@field='#{fieldx}']"]
    parameter.add_attribute('value', valuex)
    parameter
    
    rescue
      puts 'feedpopulated.rb: map_attr() the field ' + fieldx + ' was not found in params.'
      raise
    end
  end

Notice that a raise statement is used to ensure that the system error message is raised and any further code execution is halted.

Without adding a customized helpful message I would be left scratching my head trying to work out what the following system error message meant.
./feedpopulated.rb:27:in `map_pattr': undefined method `add_attribute' for nil:NilClass (NoMethodError)
     from ./feedpopulated.rb:51:in `create_record'
     from ./feedpopulated.rb:49:in `each'
     from ./feedpopulated.rb:49:in `create_record'
     from ./recordx.rb:91:in `call_create'
     from ./s3fileuploader_handler.rb:14:in `call'
     from ./s3fileuploader_handler.rb:40:in `invoke'
     from ./uploadtwitteraudio.rb:22:in `initialize'
     from /usr/lib/ruby/1.8/rexml/element.rb:890:in `each'
     from /usr/lib/ruby/1.8/rexml/xpath.rb:53:in `each'
     from /usr/lib/ruby/1.8/rexml/element.rb:890:in `each'
     from ./uploadtwitteraudio.rb:18:in `initialize'
     from ./uploadtwitteraudio.rb:72:in `new'
     from ./uploadtwitteraudio.rb:72


Reference: Programming Ruby: The Pragmatic Programmer's Guide - Exceptions, Catch, and Throw [ruby-doc.org]

MySQL error reporting

MySQL error reporting

$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $query . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());

Full information for Ruby errors

Sometimes I want to be able to print out everything about an error: it's class, message and the stack trace. So how about this:

Update: followed suggestion by onarap and changed the line breaks to $/. No syntax highlighting because the code breaks the snippet parser.


class StandardError
def info
"#{self.class}: #{message}#$/#{backtrace.join($/)}"
end
end

Let php show all errors

I have wondered why my php script doesn't show
errors like it did before. It seems my server admin
has default config set not to show the errors.

Here's how to override it.
error_reporting(E_ALL);
ini_set('display_errors', '1');


BTW, it's really a pain to code in a language that
demand a ';' after every line.

Converting old PHP Errors into Exceptions

The PHP5 Exception class will not work correctly. It would reflect an incorrect line number and file name and not record the 'errcontext' value associated with PHP errors. To solve this problem, we must extend the Exception class.
/**
 * This exception behaves like a "old school" PHP Error
 */
class STEM_ErrorException extends Exception
{
	/**
	 * The PHP Error Context
	 *
	 * The fifth parameter is optional, errcontext, which is an array that points to the active symbol table at the point the error occurred. In other words, errcontext  will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context.
	 */
	private $m_arContext;

	/**
	 * Constructor
	 */
	public function __construct($vMessage, $vCode, $vFile, $vLine, $arContext = null)
	{
		parent::__construct($vMessage, $vCode);
		
		$this->file = $vFile;
		$this->line = $vLine;
		
		$this->m_arContext = $arContext;
	}
}


We need to define a function to handle errors. We also want to write two helper functions that will set and restore the error handler to our function. To do this, we write three methods in an abstract class.
/**
 * STEM Error Handler
 *
 * Registers Itself as a PHP Error Handler and proceeds to convert all
 * native "old school" PHP errors into new PHP5 Exceptions.
 *
 * Call STEM_ErrorHandler::Initialize(); before your try blocks and
 * STEM_ErrorHandler::Uninitialize(); afterwards.
 */
abstract class STEM_ErrorHandler
{
	/**
	 * Encapsulates set_error_handler()
	 */
	public static function Initialize()
	{
		set_error_handler(array("STEM_ErrorHandler", "HandleError"));
	}
	
	/**
	 * Encapsulates restore_error_handler()
	 */
	public static function Uninitialize()
	{
		restore_error_handler();
	}
	
	/**
	 * Handles PHP Errors
	 */
	public static function HandleError($errno, $errstr, $errfile, $errline, $errcontext)
	{
		throw new STEM_ErrorException($errstr, $errno, $errfile, $errline, $errcontext);
	}
}


To test it, we create a file that triggers errors. Before triggering the first error, we call Initialize(). We then Uninitialize() the error handler and trigger the error again to check that our error handler has been removed. It is important to check the line numbers mentioned in the message that this prints!
STEM_ErrorHandler::Initialize();

try
{
	trigger_error("Hello World!");
}
catch (Exception $e)
{
	print $e;
}

STEM_ErrorHandler::Uninitialize();
print "<hr />";

try
{
	trigger_error("Hello World!");
}
catch (Exception $e)
{
	print $e;
}


--
Version 0.1.0 - 2006-02-14
STEM: The STEM Cells of PHP
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License
http://creativecommons.org/licenses/by-sa/2.5/

Fix for nil object error in Rails test fixtures

If you're seeing errors like this when you run Rails tests:

# NoMethodError: You have a nil object when you didn't expect it!


You might need to edit test/test_helper.rb to make sure use_instantiated_fixtures is true:

self.use_instantiated_fixtures = true


Prior to 1.0, Rails automatically created instance variables out of fixtures. So if you had a fixture record named "foo", you could access it in your test as "@foo". As of 1.0, the default is to disable that feature, which breaks a lot of existing code. Mike Clark explains the change.

TryCatch: simple try catch block in perl

### begin_: file metadata
    ### <region-file_info>
    ### main:
    ###   - name    : TryCatch: try catch block
    ###     desc    : a simple try-catch block example in perl
    ###     date    : created="Thu 2005-12-01 10:58:09"
    ###     last    : lastmod="Thu 2005-12-01 10:58:13"
    ###     tags    : try catch finally error perl cfTryCatch exception
    ### </region-file_info>

### begin_: init perl
    use strict;
    use warnings;

### begin_: try-catch block
    print "begin \n";
    eval{
        ### try block
        print Non_Existent_Function();
    };
    if ($@){
        ### catch block
        print "Failed \n";
    };
    print "end \n";
« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS