简体   繁体   中英

Why is my exception not picked up by jquery ajax call to controller?

I'm working on a button that calls an action in my asp.net mvc controller. I'm trying to catch errors and display them to the user in a decent way, but I can't seem to figure out how to do this properly. Whenever I force an exception (for testing purposes) in my controller, the .sucess part of my ajax call i still fired. Here's my ajax call:

$(document).ready(function() {
    $("#del").on("click", function() {
        var message;
        $.ajax({
            url: "@Url.Action("DeleteImage", "UnitSummary")",
            type: "GET",
            dataType: "json",
            data: { unitId: "@Model.UnitId" },
            error: function(msg) {
                message = msg;
                $('#delsection').hide().html('<div class="alert alert-danger"><strong>Ouch!</strong> ' + message.statusText + '</div>').fadeIn('slow');
            },
            success: function(msg) {
                message = msg;
                $('#delsection').hide().html('<div class="alert alert-success"><strong>Success!</strong> Image was deleted.</div>').fadeIn('slow');
            }
        });
    });

And here's my controller:

[HttpGet]
public ActionResult DeleteImage(int unitId)
{
    try
    {
        throw new Exception("Forced error");
        UnitClient.UpdateUnitImage(unitId, new byte[0]);
    }
    catch (Exception e)
    {
        Log.Error(e);
        return Json(new { e.Message }, JsonRequestBehavior.AllowGet);
    }

    return Json(new JsonResult(), JsonRequestBehavior.AllowGet);
}

Sucess always gets called, even though the image is not deleted. What am I missing here?

Whenever I force an exception (for testing purposes) in my controller, the .sucess part of my ajax call i still fired.

The following line of code is not an exception that jQuery's ajax interprets as an error response from the server (hence no call to the error callback), but a regular 200 OK response:

return Json(new { e.Message }, JsonRequestBehavior.AllowGet);

Do it like this instead:

return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Message);

This is where HTTP status codes come into play, BadRequest is an HTTP error status code.

Here's more about BadRequest :

Equivalent to HTTP status 400. BadRequest indicates that the request could not be understood by the server. BadRequest is sent when no other error is applicable, or if the exact error is unknown or does not have its own error code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM