简体   繁体   English

如何从异常中获取消息错误 Ajax MVC 5 核心

[英]How to get message error from Exception whit Ajax MVC 5 core

I'm trying to fill Field with user information using ajax.我正在尝试使用 ajax 用用户信息填充字段。 It work well;它运作良好;

ACTION行动

  public Operatore User(int Id)
        {
            Operatore User = new Operatore();

            /*
             DO STUFF TO FILL USER

             */

            /*if something go wrong 
              throw new Exception("user does not exist");
             */


            return User;
        }

but if i throw Exception with custom message i can't read it in Ajax但是如果我使用自定义消息抛出异常,我将无法在 Ajax 中读取它

AJAX AJAX

     $.ajax({
                        type: "GET",
                        contentType: "application/json; charset=utf-8",
                        url: "@Url.Action("User")",
                        data: { Id: $("#ID").find(":selected").val()},
                        success: function (msg) {
                        /*FILL THE DATA*/
                        /*It works well*/
                        },
                        error: function (error) {
                            alert(error.Message);
                           /*this does not work*/
                        }
                    });

I just need to read my custom error message.我只需要阅读我的自定义错误消息。 The alert return "undefined" How can i do?警报返回“未定义”我该怎么办?

If something goes wrong (in operatore):如果出现问题(在操作员中):

Response.StatusCode = 500;
Return Json("Error Message");

StatusCode is necessary to mislead Ajax. StatusCode 是误导 Ajax 所必需的。 Beware your action must return an object.请注意,您的操作必须返回 object。

In Ajax:在 Ajax 中:

 error: function (error) {
        alert(error.responseJSON);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM