ASP.NET MVC receives exception message in Ajax

I have an action:

[HttpPost]
public ActionResult MyAction(MyModel model)
{
    ...
    if (model.MyCondition == true)
        throw new Exception("MyMessage);
    ....
}

I would like to receive the “MyMessage” message from Ajax:

onSuccess: function () {
...
},
onError: function (jqXHR, textStatus, errorThrown) {
//I'd like get "MyMessage" here
}

Idea how to do this? When I check with the debugger, I do not see my line.

+5
source share
4 answers

Implementing an error attribute is a good way. In addition, I usually do not throw exceptions, but return a status code according to the error. You can write your response stream and access through js via XMLHttpRequest.responseText:

if (model.MyCondition == true)
{
    if (Request.IsAjaxRequest())
    {
        Response.StatusCode = 406; // Or any other proper status code.
        Response.Write("Custom error message");
        return null;
    }
}

and in js:

...
error: function (xhr, ajaxOptions, errorThrown) {
    alert(xhr.responseText);
}
+8
source

Try returning a ContentResult from your action with an action of type GET.

[HttpGet]
public ContentResult MyAction(String variablename)
{
    ...
    if (some_verification == true)
        return Content("MyMessage);
    ....
}

On the watch page

$.ajax({
    url: 'your controller/action url',
    type: 'get',
    cache: false,
    async: false,
    data: { variablename: "value" },
    success: function (data) {
        alert(data);
    },
    error: function () {
        alert('Error doing some work.');
    }
});
0

ErrorAttribute:

[NonAction]
protected void OnException(ExceptionContext filterContext)
{

    this.Session["ErrorException"] = filterContext.Exception;

    if (filterContext.Exception.GetType() == typeof(MyException))
    {
        // Mark exception as handled
        filterContext.ExceptionHandled = true;
        // ... logging, etc
        if (Request.IsAjaxRequest())
        {
            /* Put your JSON format of the result */
            filterContext.Result = Json(filterContext.Exception.Message);
        }
        else
        {
            // Redirect
            filterContext.Result = this.RedirectToAction("TechnicalError", "Errors");
        }
    }
}

.

You can also override your controller's OnException method, but I believe the user attribute is more flexible.

0
source

Perhaps you could create a BaseController class where you override the Controller method OnException(ExceptionContext filterContext)and convert the exceptions to JSON so that you can easily handle them from the JavaScript client.

0
source

All Articles