Chorn Sokun's Weblog

Conquer inner fear, push it to the limit!

Use jQuery to catch and display MR AJAX errors

with one comment

This post influenced Dave Ward’s post to replicate the behavior that he discussed within MonoRail application.  To mimic this behavior I created a method call RenderJsonError(Exception ex) inside my base controller (I want to reuse this method)

public abstract class AbstractBaseController: ARSmartDispatcherController{
   private void RenderJsonError(Exception ex){
      CancelLayout();
      Response.StatusCode = 500;
      Response.ContentType = "application/json; charset=utf-8";

      // I love this Framework :)
      var json = Context.Services.JSONSerializer.Serialize(
         new ErrorObject(){
            Message = e.Message,
            StackTrace = e.StackTrace
         });

      RenderText(json);
   }
}

From the code above look like I need to create a dummy DTO class ErrorObject and hand it over to JSONSerializer service instead of doing string escape/string concat myself :) MR use Newtonsoft.Json.dll behind the scene.

public abstract class AbstractBaseController: ARSmartDispatcherController{
  ....
  internal class ErrorObject{
     public string Message { get; set; }
     public string StackTrace { get; set; }
  }
}

Now let through some booms back to client

public class HomeController: AbstractBaseController{
   public void Index(){
      try{
          throw new Exception("Boom ! boom !");
      }catch(Exception ex){
          RenderJsonError(ex);
      }
   }
}

That work ! however if you don’t want to deal with try{..} catch {..} then combine this technique with RescueAttribute describe in my previous post.

Advertisements

Written by Chorn Sokun

October 2, 2009 at 12:58 am

Posted in MonoRail

Tagged with ,

One Response

Subscribe to comments with RSS.

  1. Hi,

    You use ex as argument, yet you use e when accesing the exception:

    RenderJsonError(Exception ex){

    Message = e.Message,
    StackTrace = e.StackTrace

    Dan

    Dan

    March 19, 2010 at 11:04 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: