如何向 $.ajax 报告错误而不在 MVC 控制器中抛出异常? [英] How to report error to $.ajax without throwing exception in MVC controller?

查看:23
本文介绍了如何向 $.ajax 报告错误而不在 MVC 控制器中抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a controller, and a method as defined...

[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...

}

异常问题

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

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

I need some easy way to report some custom http status to my $.ajax call so that it should result an error at client side, but I do not want to throw an error.

更新

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

I cannot change client script because it becomes inconsistent with other data source.

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

So far, HttpStatusCodeResult should work but it's IIS that is causing the problem here. No matter what error message I set, tried all answers, still I receive default message only.

推荐答案

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

This is where HTTP status codes come into play. With Ajax you will be able to handle them accordingly.

[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.
}

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

这篇关于如何向 $.ajax 报告错误而不在 MVC 控制器中抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆