Tuesday, 31 January 2017

ASP.NET MVC $.ajax error handling

Problem:
I tried inside my (classic) MVC web application to show custom error(message)s when using $.ajax(). Several options tried, like:
return new HttpStatusCodeResult(401, "Custom Error Message 1");
but no luck. On some weird way, the error was not cached inside my $.ajax().error(...)

Solution:
I wrote a custom extension method on Controller level:
public static class ControllerExtensions
{
 public static ContentResult CustomError(this Controller ctl, int statuscode, string message)
 {
  ctl.Response.ContentType = "application/json";
  ctl.Response.StatusCode = statuscode;
  ctl.Response.Write(message);
  return new ContentResult();
 }
}

So, inside my controller actions, I can just call:
 return this.CustomError(400, myerrormessage);

On the view I now can just do the following:
$.ajax({
 // do you stuff here
 success: function (response) {
  // do success response actions
 },
 error: function (data, textStatus, jqXHR) {
  // the 'data' contains data.responseText, which is the 'myerrormessage' entered into the extension method
  // 'data' contains data.status, which is the statuscode entered into the extension method (400)
  toastr["error"]("Error(s) during loading group list:
" + data.responseText);
 }


Well, that's it for me. It might be useful for you :)

3 comments:

buy college essays said...

A very helpful blog post. I really like they way you jotted down the process. First analyse the problem and then provided the best possible solution to it. Good job

Rob said...

Thanks 'buy college essays'.

Motor Vehicle Accident in CA said...

You adopted a very user friendly way to explain the situation. Easy for anyone to understand. Keep writing more of such blog post and adopt the same process.