2

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??

David Shochet
  • 5,035
  • 11
  • 57
  • 105
  • [How to report error to $.ajax without throwing exception....](https://stackoverflow.com/questions/8702103/how-to-report-error-to-ajax-without-throwing-exception-in-mvc-controller) Is it this? – gaetanoM Jun 11 '19 at 19:40
  • @gaetanoM Thank you for your suggestion. Unfortunately, that solution is not for MVC Core, it returns HttpStatusCodeResult. MVC Core uses StatusCodeResult instead, and its constructor takes only one argument, i.e. status code, and no error message... – David Shochet Jun 11 '19 at 19:50
  • I used return StatusCode(404, new { Message = ex.Message }); with the same result... – David Shochet Jun 11 '19 at 19:56

1 Answers1

2

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.");
});
Ryan
  • 19,118
  • 10
  • 37
  • 53