David Shochet
David Shochet

Reputation: 5395

How can I return error message to Ajax call

I have a new Mvc Core application. I use jquery to make an ajax call to my controller. I am trying to return an error message in case of an exception in the controller. Here is my code sample:

    public async Task<IActionResult> UpdateAllocations([FromBody]AllocationsDto allocationsDto)
    {
 ...
            catch (Exception ex)
            {
                Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;

                return Json(new { success = false, responseText = ex.Message });

            }

...

  $.ajax({
        type: "POST",
        url: "/Allocation/UpdateAllocations",
        data: JSON.stringify(allocationData),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    })
        .done(function (data) {

        })
        .fail(function (xhr, status, error) {
            displayError("The ajax call to UpdateAllocations() action method failed:",
                error, "Please see the system administrator.");
        });

But the error parameter is empty, and status has only one word "error" as well as xhr.statusText. How can I return my own custom text, in this case ex.Message??

Upvotes: 2

Views: 4380

Answers (1)

Ryan
Ryan

Reputation: 20139

Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."

You need to get the message from responseJSON of the first argument.

.fail(function (xhr, status, error) {

       displayError("The ajax call to UpdateAllocations() action method failed:",
                    xhr.responseJSON.responseText, "Please see the system administrator.");
});

Upvotes: 2

Related Questions