首页 > 解决方案 > 如何捕获可能的错误消息并将其转移到甜蜜警报

问题描述

在删除按钮上,我显示正常工作的甜蜜警报。问题是当我发送不存在的对象 id 时,我收到相同的消息(我成功删除)。

我想要的是在发生任何错误时显示一条消息(例如,找不到具有该 id 的事件,我想创建新消息并将其显示为一个甜蜜的警报)。

$('.deleteEvent').on('click', function () {
    var $button = $(this);
    var id = $button.data('id');
    console.log("id", id);
    var config = {
        title: 'Are you sure',
        type: 'info',
        showCancelButton: true,
        confirmButtonText: 'Yes',
        cancelButtonText: ' No',
        closeOnConfirm: false,
        closeOnCancel: true
    };

    swal(config, function (isConfirm) {
        if (isConfirm) {
            console.log("lokac", window.location.origin);
            var url = window.location.origin + '/events/delete?id=' + id;
            $.post(url)
                .done(function () {
                    var doneConfig = {
                        title: 'Succ....',
                        type: 'success',
                        confirmButtonText: 'Ok'
                    };

                    sweetAlert(doneConfig, function (done) {
                        if (done) {
                            window.location.reload();
                        }
                    });
                })
                .fail(function (error) {
                    var errorConfig = {
                        title: 'Not Found',
                        type: 'error',
                        confirmButtonText: 'Ok'
                    };
                    sweetAlert(errorConfig, function (done) {
                        if (done) {
                            window.location.reload();
                        }
                    });
                });
        }
    });
});

还有我的控制器

 public ActionResult Delete(int id)
 {
        if (id == default(int))
            return RedirectToRoute(AppRoute.Events.EventsRoute);
        id = -1;
     try
      {
            var event = 
        DbContext.Event.FirstOrDefault(x => x.EventId == id);

            if (event == null)
            {
             //If event is not found, I want to create a message which
             //will be displayed on sweet alert                   
            }
      }
   //.....
  }

标签: c#asp.netasp.net-mvcsweetalert

解决方案


考虑到执行失败函数的 HTTP 状态代码必须不同于 200 OK,因此例如,在您的控制器中,如果出现故障,您可以返回 HTTP 状态代码 500(内部服务器错误),它将执行失败函数。

在您的示例中必须类似于:

if (event == null)
  {
     //If event is not found, I want to create a message which
     //will be displayed on sweet alert   
     return HttpStatusCodeResult(500)
  }

如果您想显示不同的消息,您应该在 .done 和 .fail 函数中捕获 HTTP 状态代码,并根据您从服务器获得的内容显示一条消息


推荐阅读