我有一个新的 Mvc Core 应用程序。我使用 jquery 对我的 Controller 进行 ajax 调用。我试图在 Controller 出现异常时返回错误消息。这是我的代码示例:
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.");
});
但是error参数为空,status只有一个字“error”以及xhr.statusText。如何返回我自己的自定义文本,在本例中为 ex.Message??
最佳答案
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."
您需要从第一个参数的responseJSON中获取消息。
.fail(function (xhr, status, error) {
displayError("The ajax call to UpdateAllocations() action method failed:",
xhr.responseJSON.responseText, "Please see the system administrator.");
});
关于jquery - 如何向 Ajax 调用返回错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56550572/