Be careful how you “cast” Error objects in AS3!

I was doing some testing of my crash reporting class I wrote for our AIR app. The getStackTrace method I was calling on the error object though was completely wrong. Here is the code I had:

[code lang="as3"]
protected static function getExtraReportInfo(error : Object, userEmail : String, userDescription : String) : String
{
var stackTrace : String;
if (error is Error)
{
stackTrace = Error(error).getStackTrace();
}
}

[/code]

That was always returning the stack trace of the getExtraReportInfo function! It was NOT returning the stack trace of the error when it was thrown! I then tried this line of code instead, and it worked:

[code lang="as3"]
stackTrace = (error as Error).getStackTrace();
[/code]

The reason it worked is that the Error(error) is not actually a cast. I believe it’s constructing a new Error instance based on the error object I’m passing in. The second example above IS a real cast, so I got the results I was expecting.

I wish casting syntax was not the same as construction syntax. Then we could avoid these sorts of bugs. I don’t normally do these sorts of inline casts anyway, but here is my working code now:

[code lang="as3"]
protected static function getExtraReportInfo(errorObj : Object, userEmail : String, userDescription : String) : String
{
var stackTrace : String = "";
var castError : Error = errorObj as Error;

if (castError != null)
{
stackTrace = castError.getStackTrace();
}
}

[/code]

Tags: ,

One Response to “Be careful how you “cast” Error objects in AS3!”

  1. After24 February 14, 2013 at 11:42 am #

    thank you very much,

    You save my day :-)

Leave a Reply