views:

29

answers:

2

When any exception occurs on the ASP.MVC server side code, I would like to take the entire stack trace of the exception and place in the ViewData and returns to the client. For example:

try
{
    //some code
}
catch (SomeException e)
{        
    ViewData["exceptionStack"] = e.StackTrace;
}

The JavaScript on the client side would just take the string in the ViewData and display it. For example:

<script type="text/javascript">
    var exceptionStack = '<%= ViewData["exceptionStack"] %>';
</script>

The problem is how I can ensure, either via regex or other means, either on the server side using C# or on the client that the JavaScript variable exceptionStack would NOT contain any illegal character, so that when I do:

$('#someElement').text(exceptionStack);

or

$('#someElement').html(exceptionStack);

there won't be any error.

+1  A: 

The method you are looking for is HtmlHelper.Encode:

<script type="text/javascript">
    var exceptionStack = '<%= Html.Encode(ViewData["exceptionStack"] %>)';
</script>
Wyatt Barnett
ckramer's answer much better.
Wyatt Barnett
+2  A: 

I would say that using HtmlEncode would work. So from the controller:

// Stuff in the controller action that may cause an error
catch(Exception ex)
{
    ViewData["exceptionStack"] = Server.HtmlEncode(ex.ToString());
}

If for some reason Html Encoding doesn't work for you, or you want to be extra secure, you can also use the AntiXSS library:

// Stuff in the controller action that may cause an error
catch(Exception ex)
{
    ViewData["exceptionStack"] = AntiXss.JavaScriptEncode(ex.ToString());
}

The HtmlEncoding is available as an HtmlHelper:

<%= Html.Encode(ViewData["exceptionStack"]) %>

And you can easily create wrappers for the AntiXSS libraries

public static string JavaScriptEncode(this HtmlHelper helper, string input)
{
    return AntiXss.JavaScriptEncode(input);
}

Which can then be used in the same way:

<%= Html.JavaScriptEncode(ViewData["exceptionStack"]) %>

Of course AntiXSS also has encoding for Html, XML, VBScript and Url encoding, so you could add a helper for any or all of those.

ckramer