Mvc 异常处理 ajax的 和 不是ajax的!

时间:2024-07-01 14:36:20
using ImageUpload.Auth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc; namespace Web
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class HandleAjaxErrorAttribute : FilterAttribute, IExceptionFilter
{ public void OnException(ExceptionContext filterContext)
{ var errorMsg = filterContext.Exception.Message;
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);
filterContext.ExceptionHandled = true;
}
else
{
Er.G(errorMsg);//把错误存储起来
filterContext.Result = new RedirectResult("/Home/ErrorMsg/");
filterContext.ExceptionHandled = true;
}
}
protected JsonResult AjaxError(string message, ExceptionContext filterContext)
{
//如果消息是null或空,则充满了通用的消息
if (String.IsNullOrEmpty(message))
message = "发生了一些错误在处理您的请求。请刷新页面再试一次."; //响应状态代码设置为500
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; //需要 IIS7.0
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; return new JsonResult
{
//可以扩展更多的属性
Data = new AjaxExceptionModel() { ErrorMessage = message },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
}
public class AjaxExceptionModel
{
public string ErrorMessage { get; set; }
}
}

Er 类用来存储错误信息 然后前台调用

    public static class Er
{
public static string Msg { get; set; }
/// <summary>
/// 将错误信息存起来
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string G(string s)
{
Msg = s;
return Msg;
}
/// <summary>
/// 读取错误信息
/// </summary>
/// <returns></returns>
public static string P()
{
return Msg;
} }

创建一个ErrorMsg控制器 和  视图

  public ActionResult ErrorMsg()
{
string ss = Er.P();
ViewBag.msg = Er.P();
return View();
}

视图

@{
ViewBag.Title = "";
Layout = "~/Views/Shared/_Layout.cshtml";
} <div id="div" style="display:none">
<h2>@ViewBag.msg </h2>
<h3><a href="/Home/Index">返回首页</a></h3>
<p>给您造成影响,再次向您表示道歉!</p>
</div> @section scripts
{
<script> @if (ViewBag.msg!=null)
{
<text>
swal(
{
title: "错误?",
text: "@ViewBag.msg!",
type: "error",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "跳到首页",
cancelButtonText: "不",
closeOnConfirm: false,
closeOnCancel: false,
allowOutsideClick:true
},
function (isConfirm) {
if (isConfirm) {
window.location.href = "/Home/Index";
swal("请等待!", "正在跳转。。。", "success");
} else {
swal(
{
title: "取消",
text: "您取消了跳转.",
type: "warning",
confirmButtonText:"确定",
timer:
});
$("#div").show();
}
});
</text>
} </script>
}

视图用到了sweetalert  弹窗插件

下面是ajax的全局错误处理

创建一个 MyJs 的js文件

$(document).ajaxError(function (event, xhr, options, exc) {
if (xhr.responseText != "") {
var jsonValue = jQuery.parseJSON(xhr.responseText);
console.log(jsonValue.ErrorMessage);
swal(
{
title: "错误",
text: jsonValue.ErrorMessage,
type: "warning",
confirmButtonText: "确定",
});
}
})