0

I have developed my application in ASP.net MVC5 using ServiceStack framework. In my app, on button click, I make ajax server call which returns data.

this.LoadData = function(){
    $.ajax({
        url: '@Url.Action("SearchCustomer", "Customer")',
        cache: false,
        type: 'GET',
        contentType: 'application/json',
        data: { 'IndexNo': this.IndexNo },
        success: function (result) {
        },
        error: function (xhr, status, error) {
        }
    });
}

In some circumstances, my service layer throws exception (which I understand should get serialized into the ResponseStatus object of Response DTO). In the error function of above ajax call, I want to retrieve the custom exception message which my service layer throws. How I can achieve that? status and error above holds the serialized ResponseStatus information i.e. "Internal server error", error code 500 etc. What I want is custom error message thrown by my service layer.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
user2185592
  • 368
  • 1
  • 8
  • 24

3 Answers3

0

I don't think you'll find a single simple solution to generating and returning exceptions from an MVC5 application. However, there are numerous posts and answers related to this topic:

https://stackoverflow.com/a/29481150/571237

...and here's a blog post that provides some additional detail:

http://www.dotnetcurry.com/showarticle.aspx?ID=1068

Once you work out how to generate and return the exception to the javascript client, it's just a matter of parsing the response on the client to extract the exception details you created on the server. If you're unsure what the variables are in the error handler above you could inspect them with any of the available javascript debugging tools available in Chrome/Firefox/IE/etc.

Community
  • 1
  • 1
Sam Storie
  • 4,444
  • 4
  • 48
  • 74
0

You should be able to parse the error response body as JSON and access the ResponseStatus with:

error: function (xhr, status, error) {
    try {
        var response = JSON.parse(xhr.responseText);
        console.log(response.ResponseStatus);
    } catch (e) { }
}
mythz
  • 141,670
  • 29
  • 246
  • 390
0

I did following in order to fix my problem :

  1. I handled the WebServiceException in my controller method and in catch block I rethrow the exception by filling in required details (mainly my custom exception message from server). Controller method is decorated with "HandleExceptionAttribute"

    [HandleExceptionAttribute]
    public JsonResult SearchCustomer(string IndexNo)
    {
        var client = new JsonServiceClient(ConfigurationManager.AppSettings["baseURL"]);
        GetCustomerResponse response = null;
    
        CustomerViewVM viewVM = null;
        try
        {
            response = client.Get<GetCustomerResponse>(<RequestDTOObjet>);
    
            viewVM = response.ToViewCustomerVM();
        }
        catch(WebServiceException ex)
        {
            Exception e = new Exception(ex.ErrorMessage);
            e.Data.Add("Operation", "View Customer");
            e.Data.Add("ErrorCode", ex.StatusCode);
    
            throw e;
        }
    
        return Json(viewVM, JsonRequestBehavior.AllowGet);
    }
    
  2. wrote "HandleExceptionAttribute". Here I wrap my exception message as Json object and set status code.

    public class HandleExceptionAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
            {
                if (filterContext.Exception.Data["ErrorCode"] != null)
                {
                    filterContext.HttpContext.Response.StatusCode = (int)Enum.Parse(typeof(HttpStatusCode), 
                                                                        filterContext.Exception.Data["ErrorCode"].ToString());
                }
    
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        filterContext.Exception.Message,
                    }
                };
                filterContext.ExceptionHandled = true;
            }
            else
            {
                base.OnException(filterContext);
            }
        }
    }
    
  3. Then inside my ajax calls error function, I parse the json object which has information about the custom error message (which I have set in attribute class)

    error: function (xhr, textStatus, errorThrown) {
         var err = JSON.parse(xhr.responseText);
         var msg = err.Message;
    }
    

That's how I managed to get the custom error message from my service layer. Hope this is how it should be done. If experts here have any suggestion on above solution then pls comment.

Mythz and Sam thanks for your answers.

user2185592
  • 368
  • 1
  • 8
  • 24