【问题标题】:How to get message error from Exception whit Ajax MVC 5 core如何使用 Ajax MVC 5 核心从异常中获取消息错误
【发布时间】:2022-01-23 21:29:16
【问题描述】:

我正在尝试使用 ajax 用用户信息填充字段。 效果很好;

动作

  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;
        }

但是如果我抛出带有自定义消息的异常,我无法在 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*/
                        }
                    });

我只需要阅读我的自定义错误消息。 警报返回“未定义” 我该怎么办?

【问题讨论】:

  • this does not work 是什么意思?
  • 不要使用alert进行调试,正确调试,或者至少使用console.log,因为它会输出对象-console.log(error)然后查看显示的内容,看看你的消息在不同的财产下。
  • 请注意,您通常可以在web.config中配置是否或不错误消息传递到前端。如果它们在该级别被阻止,您将无法在您的 js 中获取它们。

标签: javascript c# jquery asp.net-mvc


【解决方案1】:

如果出现问题(在操作员中):

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

StatusCode 是误导 Ajax 所必需的。 请注意,您的操作必须返回一个对象。

在阿贾克斯中:

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

【讨论】:

    猜你喜欢
    • 2017-02-11
    • 2014-08-11
    • 1970-01-01
    • 2011-05-26
    • 2016-03-18
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多