Throw new Exception with AjaxPro

Michael Schwarz on Monday, July 30, 2007

Last Friday I had a discussion with Kris about some problems [1] he had with Ajax.NET Professional. The thing was that he was using Response.Write somewhere in his code to write exception details to the output, but that failed because the result was not a JSON response.

The simpliest way to get exception details on the client side is to throw a System.Exception or any inherited exception class of your own.

public static bool MyTest (bool x)
if (!x) throw new Exception ("This should never happen.");

return true; } ```

On the client-side JavaScript code you can then access this message in the callback method:

<pre class="csharpcode">function callback(res) {
<span class="kwrd">if</span>(res.error != <span class="kwrd">null</span> &amp;&amp; res.error.Message == <span class="str">"..."</span>) {
alert(<span class="str">"Failed: "</span> + res.error.Message);
<span class="kwrd">return</span>;
<span class="rem">// code if there is no error</span>

If you throw your own exception type you can check for the type like this:

<pre class="csharpcode">function callback(res) {
<span class="kwrd">if</span>(res.error != <span class="kwrd">null</span>) {

<span class="kwrd">switch</span>(res.error.Type) { <span class="kwrd">case</span> <span class="str">"System.IO.FileNotFoundException"</span>: <span class="rem">// ...</span> <span class="kwrd">break</span>; <span class="kwrd">case</span> <span class="str">"MyNamespace.MyException"</span>: <span class="rem">// ...</span> <span class="kwrd">break</span>; } <span class="kwrd">return</span>; } <span class="rem">// code if there is no error</span> }</pre>