Throw new Exception with AjaxPro

Tags: .NET, AJAX, Ajax.NET, JavaScript, Source Code

Last Friday I had a discussion with Kris about some problems 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.

[AjaxPro.AjaxMethod]
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:

function callback(res) {
    if(res.error != null && res.error.Message == "...") {
        alert("Failed: " + res.error.Message);
        return;
    }
    // code if there is no error
}

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

function callback(res) {
    if(res.error != null) {

        switch(res.error.Type) {
            case "System.IO.FileNotFoundException":
                // ...
                break;
            case "MyNamespace.MyException":
                // ...
                break;
        }
        return;
    }
    // code if there is no error
}

1 Comment

Comments have been disabled for this content.