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 

Flex/ActionScript: Making trace() display the method it was called in

While trace() is useful, its indiscriminate use by me often crowds
the console of my fellow developers. We agreed on making every trace() show
the method it came from, but I am too lazy to do this, this makes it automatic:

public static function TRACE(s:Object):void {
  try {
    throw new Error();
  } catch (e:Error) {
    var stack:String = e.getStackTrace();
    var frames:Array = stack.split("\n");
    var myFrame:String = String(frames[2]);
    myFrame = myFrame.replace("\t", "");
  
    // "at " can be followed by some part of the package
    // you don't want to see. E.g., if your code is all in
    // com.foo.bar, you can put "at com.foo.bar." so as not
    // to crowd the display
    myFrame = myFrame.substr("at ".length);
    myFrame = myFrame.substring(0, myFrame.indexOf("["));
    trace(myFrame + ": " + s);
  }
}

Python - Exception CGI Redirect

// Reindirizza gli errori di uno script CGI in un file random nella cartella /tmp

import cgitb; cgitb.enable(display=0, logdir='/tmp')

Exception class fix for php 4 //PHP Class

if(!class_exists('Exception')){
	class Exception{
		var $_message = '';
		var $_code = 0;
		var $_line = 0;
		var $_file = '';
		var $_trace = null;

		function Exception($message = 'Unknown exception', $code = 0){
			$this->_message = $message;
			$this->_code = $code;
			$this->_trace = debug_backtrace();
			$x = array_shift($this->_trace);
			$this->_file = $x['file'];
			$this->_line = $x['line'];
		}

		function __construct($message = 'Unknown exception', $code = 0){
			$this->Exception($message, $code);
		}

		function getMessage(){
			return $this->_message;
		}
		function getCode(){
			return $this->_code;
		}
		function getFile(){
			return $this->_file;
		}
		function getLine(){
			return $this->_line;
		}
		function getTrace(){
			return $this->_trace;
		}
		function getTraceAsString(){
			$s = '';
			foreach($this->_trace as $i=>$item){
				foreach($item['args'] as $j=>$arg)
					$item['args'][$j] = print_r($arg, true);
				$s .= "#$i " . (isset($item['class']) ? $item['class'] . $item['type'] : '') . $item['function']
				. '(' . implode(', ', $item['args']) . ") at [$item[file]:$item[line]]\n";
			}
			return $s;
		}
		function printStackTace(){
			echo $this->getTraceAsString();
		}
		function toString(){
			return $this->getMessage();
		}
		function __toString(){
			return $this->toString();
		}
	}
}

C# Reflection - Dealing with AmbiguousMatchException

C# code invoking a static method with reflection and dealing with an AmbiguousMatchException
Source: http://msdn2.microsoft.com/en-US/library/xthb9284.aspx


class Myambiguous {
    //The first overload is typed to an Int32
    public static void Mymethod (Int32 number){
       Console.Write("\n{0}", "I am from Int32 method");
    }

    //The second overload is typed to a string
    public static void Mymethod (string alpha) {
       Console.Write("\n{0}", "I am from a string.");
    }
    
    public static void Main() {
        try {
            //The following does not cause as exception
            Mymethod (2);  // goes to Mymethod (Int32)
            Mymethod ("3");   // goes to Mymethod (string)

            Type Mytype = Type.GetType("Myambiguous");

            MethodInfo Mymethodinfo32 = Mytype.GetMethod("Mymethod", new Type[]{typeof(Int32)});
            MethodInfo Mymethodinfostr = Mytype.GetMethod("Mymethod", new Type[]{typeof(System.String)});

            //Invoke a method, utilizing a Int32 integer
            Mymethodinfo32.Invoke(null, new Object[]{2});

            //Invoke the method utilizing a string
            Mymethodinfostr.Invoke(null, new Object[]{"1"});

            //The following line causes an ambiguious exception
            MethodInfo Mymethodinfo = Mytype.GetMethod("Mymethod");
        }  // end of try block
  
        catch(System.Reflection.AmbiguousMatchException theException) {
            Console.Write("\nAmbiguousMatchException message - {0}", theException.Message);
        }
        catch {
            Console.Write("\nError thrown");
        }
        return;
    }
}
 
 //This code produces the following output:
 //I am from Int32 method
 //I am from a string.
 //I am from Int32 method
 //I am from a string.
 //AmbiguousMatchException message - Ambiguous match found.

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/

All Exceptions Created Equal

All exceptions are created equal. But what if you have a very good and pressing reason to serialize one to save it in a database? For instance, you had a collection of checks you wanted to run against some data, and save the results?

Ah, that's easy! serialize() was made for that! So off you trot, you make a few changes to the code, add a blank line here, a blank line there, and suddenly your code can't find the exact matches of the serialized object in the database.

HUH? What's going on? You're the exact same Exception I just threw three minutes ago, and you've sporadically broken?

It took me a while to twig. When you create an exception ($e = new Exception("foo");), it's shiny and new and listens when you do equality comparisions (==).

But things go awry: you throw a new Exception from your filter, catch it, and serialize it. You haven't remembered that...


$a = new Exception("foo");
try {
    throw $a; //Line 1
} catch (Exception $e) {
    throw $a; //Line 10;
}



will result in two difference traces. One saying "I was thrown on on line 1", the other "I was thrown on on line 10"...

Fuck oath, hello stupid coder. You've been wracking your brains wondering why every time you go off and edit a different bit of code it serializes differently; and there you have it.

How the hell do I fix it? Going to __sleep() on the job actually helps.



<?php
class DumbException extends Exception {
    /**
     * Cleanup anything we need before serialisation
     *
     * @return  string[]    An array of member varible names to serialize
     * @see     http://php.planetmirror.com/manual/en/language.oop5.magic.php
     */
    public function __sleep() {
        return array('string','code');
    }

    /**
     * Compare against another DumbException for equality.
     *
     * Since two exceptions can be !== because the trace / line / file
     * information is different, we need to do this.
     */
    public function cmp(DumbException $e) {
        return (serialize($e) == serialize($this));
    }
}

print '<pre>';
$a = new DumbException();
$b = new DumbException();


try {
    try {
        throw $b;
    } catch (Exception $e) {
        throw $a;
    }
} catch (Exception $e) {

    var_dump($a === $b);
    var_dump($a == $b);
    var_dump($b === $e);
    var_dump($b == $e);
    var_dump($a === $e);
    var_dump($a == $e);

    var_dump($b->cmp($e));
    var_dump($a->cmp($e));
}
print '</pre>';
?>

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