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

查看:169
本文介绍了如何报告错误$就没有在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...

}

与例外的问题

Problems with Exceptions

  1. 我们必须登录异常的情况下,如SQL连接错误的设备或网络错误。
  2. 在这些消息就像为用户的确认信息,我们不希望记录。
  3. 在抛出异常也充斥事件查看器。

我需要一些简单的方法来报告一些自定义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.

到目前为止,的HTTPStatus codeResult应该工作,但它的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状态codeS开始发挥作用。使用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.
}

这里是定义的状态codeS 的列表。

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

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