如何在不抛出MVC控制器异常的情况下向$ .ajax报告错误?

Aka*_*ava 34 c# ajax asp.net-mvc controller

我有一个控制器,和一个定义的方法......

[HttpPost]
public ActionResult UpdateUser(UserInformation model){

   // Instead of throwing exception
   throw new InvalidOperationException("Something went wrong");


   // I need something like 
   return ExecutionError("Error Message");

   // which should be received as an error to my 
   // $.ajax at client side...

}
Run Code Online (Sandbox Code Playgroud)

异常问题

  1. 我们必须在设备或网络错误(如SQL连接错误)的情况下记录异常.
  2. 这些消息就像用户的验证消息,我们不想记录.
  3. 抛出异常也会使事件查看器泛滥.

我需要一些简单的方法来报告我的$ .ajax调用的一些自定义http状态,以便它在客户端产生错误,但我不想抛出错误.

UPDATE

我无法更改客户端脚本,因为它与其他数据源不一致.

到目前为止,HttpStatusCodeResult应该可以正常工作,但这是导致此问题的IIS.无论我设置了什么错误消息,尝试了所有答案,我仍然只收到默认消息.

Den*_*aub 48

这是HTTP状态代码发挥作用的地方.使用Ajax,您将能够相应地处理它们.

[HttpPost]
public ActionResult UpdateUser(UserInformation model){
    if (!UserIsAuthorized())
        return new HttpStatusCodeResult(401, "Custom Error Message 1"); // Unauthorized
    if (!model.IsValid)
        return new HttpStatusCodeResult(400, "Custom Error Message 2"); // Bad Request
    // etc.
}
Run Code Online (Sandbox Code Playgroud)

这是已定义状态代码的列表.

  • IIS正确执行,ASP.NET开发服务器中存在错误. (6认同)
  • 我打算接受这个答案,但不幸的是,看起来 MVC 正在重写这个状态并放回它自己的消息而不是我想要发送的错误消息。 (2认同)

dkn*_*ack 9

描述

如何将对象返回到您的页面并在ajax回调中分析它.

样品

[HttpPost]
public ActionResult UpdateUser(UserInformation model)
{
    if (SomethingWentWrong)
        return this.Json(new { success = false, message = "Uuups, something went wrong!" });

    return this.Json(new { success=true, message=string.Empty});
}
Run Code Online (Sandbox Code Playgroud)

jQuery的

$.ajax({
  url: "...",
  success: function(data){
    if (!data.success) 
    {
       // do something to show the user something went wrong using data.message
    } else {
       // YES! 
    }
  }
});
Run Code Online (Sandbox Code Playgroud)


shi*_*zik 5

您可以在基本控制器中创建一个辅助方法,该方法将返回服务器错误,但带有您的自定义状态代码。例:

public abstract class MyBaseController : Controller
{
    public EmptyResult ExecutionError(string message)
    {
        Response.StatusCode = 550;
        Response.Write(message);
        return new EmptyResult();
    }
}
Run Code Online (Sandbox Code Playgroud)

需要时,您将在操作中调用此方法。在您的示例中:

[HttpPost]
public ActionResult UpdateUser(UserInformation model){

   // Instead of throwing exception
   // throw new InvalidOperationException("Something went wrong");


   // The thing you need is 
   return ExecutionError("Error Message");

   // which should be received as an error to my 
   // $.ajax at client side...

}
Run Code Online (Sandbox Code Playgroud)

错误(包括自定义代码“ 550”)可以在客户端进行全局处理,如下所示:

$(document).ready(function () {
    $.ajaxSetup({
        error: function (x, e) {
            if (x.status == 0) {
                alert('You are offline!!\n Please Check Your Network.');
            } else if (x.status == 404) {
                alert('Requested URL not found.');
/*------>*/ } else if (x.status == 550) { // <----- THIS IS MY CUSTOM ERROR CODE
                alert(x.responseText);
            } else if (x.status == 500) {
                alert('Internel Server Error.');
            } else if (e == 'parsererror') {
                alert('Error.\nParsing JSON Request failed.');
            } else if (e == 'timeout') {
                alert('Request Time out.');
            } else {
                alert('Unknow Error.\n' + x.responseText);
            }
        }
    });
});
Run Code Online (Sandbox Code Playgroud)