[英]Message thrown from catch block in Controller is not displayed properly
我试图将从ASP.NET MVC控制器引发的异常消息传递给JQuery Ajax函数。 但是该消息未正确显示。 可能是它被传递到成功块,因此显示时错误消息的颜色不正确。
在控制器中:
[HttpPost]
public string ABC()
{
try
{
//some codes here
return message;
}
catch (Exception ex)
{
return "An error has occurred.";
}
}
在Ajax函数中:-
success: function (data1) {
var message = data1;
HideMasterProcessing();
ShowNotificationMessage(message, "notifyMessage", "notify-info", false);
},
error: function (data2) {
var message = data2;
HideMasterProcessing();
ShowNotificationMessage(message, "notifyMessage","notify-errror", false);
}
我想在“ notify-error” div中显示异常消息。 但是它显示在“ notify-info” div中。
您不会从控制器返回错误状态,因此始终将结果视为成功。 使用ActionResult
作为包装器,而不是仅返回字符串,因此可以指定状态代码:
return new HttpStatusCodeResult(500, "An error occurred.");
更好地解释codroipo已经评论的内容:
当您在catch块中返回错误消息时,AJAX函数将其视为成功,这意味着它永远不会落在AJAX“错误”块上。
您可以让异常抛出并在AJAX“错误”块中对其进行处理
或者保持这种方式并返回一个compose对象,如下所示:
[HttpPost]
public string ABC()
{
try
{
//some codes here
return new {Message = message, Error = null};
}
catch (Exception ex)
{
return new {Message = null, Error = "An error has occurred."};
}
}
在Ajax函数中:
success: function (data1) {
HideMasterProcessing();
if(data1.Error == null)
{
var message = data1.Message;
ShowNotificationMessage(message, "notifyMessage", "notify-info", false);
}
else
{
var message = data1.Error;
ShowNotificationMessage(message, "notifyMessage","notify-errror", false);
}
},
error: function (data2) {
var message = data2;
HideMasterProcessing();
ShowNotificationMessage(message, "notifyMessage","notify-errror", false);
}
让我知道是否可以!
这为我工作:
[HttpPost]
public string ABC()
{
try
{
//some codes here
return message;
}
catch (Exception ex)
{
var message = "An error has occurred.";
return message;
}
}
在Ajax中:
success: function (data1) {
if (data1 === "An error has occurred.")
{
HideMasterProcessing();
ShowNotificationMessage("An error has occurred. Please contact administrator.", "notifyMessage", "notify-error", false);
}
else
{
HideMasterProcessing();
var message = data1;
ShowNotificationMessage(message, "notifyMessage", "notify-info", false);
}
我只是比较了从控制器传递的字符串和在成功块中输入的数据,然后将其显示在所需的div中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.