Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC get Exception message in Ajax

I have an action :

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

I'd like get the message "MyMessage" on the Ajax side :

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

An idea how to do this ? When I check with the debugger I don't see my string.

like image 493
Kris-I Avatar asked Nov 08 '11 11:11

Kris-I


1 Answers

Implementing an error attribute is a good way. Also, I usually don't throw the exception, but return a status code according to error. You can write to your response stream and access in 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);
}
like image 189
Kamyar Avatar answered Oct 19 '22 04:10

Kamyar