Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 723|回复: 0

ASP.NET MVC 全局异常

[复制链接]
  • TA的每日心情
    奋斗
    2024-11-24 15:47
  • 签到天数: 804 天

    [LV.10]以坛为家III

    2053

    主题

    2111

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    726782
    发表于 2021-9-2 14:39:07 | 显示全部楼层 |阅读模式

    先新建一个过滤器ExceptionHandleErrorAttribute.cs

    内容如下:

     1 using System;
     2 using System.Net;
     3 using System.Web;
     4 using System.Web.Mvc;
     5 using ABBPMP.Utility.NLogHelper.Static;
     6 
     7 namespace ABBPMP.Filter
     8 {
     9     /// <summary>
    10     /// 异常捕获(业务逻辑层,UI层)
    11     /// </summary>
    12     public class ExceptionHandleErrorAttribute : HandleErrorAttribute
    13     {
    14         /// <summary>
    15         /// 错误拦截
    16         /// </summary>
    17         /// <param name="filterContext"></param>
    18         public override void OnException(ExceptionContext filterContext)
    19         {
    20 
    21             if (filterContext.ExceptionHandled)
    22             {
    23                 return;
    24             }
    25 
    26 
    27 
    28             string message =
    29                 $"消息类型:{filterContext.Exception.GetType().Name}\r\n消息内容:{filterContext.Exception.Message}\r\n引发异常的方法:{filterContext.Exception.TargetSite}\r\n引发异常的对象:{filterContext.Exception.Source}\r\n异常目录:{filterContext.RouteData.GetRequiredString("controller")}\r\n异常方法:{filterContext.RouteData.GetRequiredString("action")}\r\n错误详细记录:{filterContext.Exception.StackTrace}";
    30             NLogHandler.Instance.Error(message);
    31             if (!filterContext.HttpContext.Request.IsAjaxRequest())
    32             {
    33                 filterContext.Controller.ViewData.Model = filterContext.Exception;
    34                 filterContext.Result = new ViewResult
    35                 {
    36                     ViewName = "~/Views/Error/Error.cshtml",
    37                     ViewData = filterContext.Controller.ViewData
    38                 };
    39             }
    40             filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);
    41 
    42 
    43 
    44 
    45             filterContext.ExceptionHandled = true;
    46         }
    47         /// <summary>
    48         /// Ajaxes the error.
    49         /// </summary>
    50         /// <param name="message">The message.</param>
    51         /// <param name="filterContext">The filter context.</param>
    52         /// <returns>JsonResult</returns>
    53         protected JsonResult AjaxError(string message, ExceptionContext filterContext)
    54         {
    55 
    56             //If message is null or empty, then fill with generic message
    57             if (String.IsNullOrEmpty(message))
    58                 message = "Something went wrong while processing your request. Please refresh the page and try again.";
    59             //Set the response status code to 500
    60             filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    61             //Needed for IIS7.0
    62             filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    63             return new JsonResult
    64             {
    65                 //can extend more properties 
    66                 Data = new AjaxExceptionModel() { ErrorMessage = message },
    67                 ContentEncoding = System.Text.Encoding.UTF8,
    68                 JsonRequestBehavior = JsonRequestBehavior.DenyGet
    69 
    70             };
    71 
    72         }
    73         /// <summary>
    74         /// AjaxExceptionModel
    75         /// </summary>
    76         public class AjaxExceptionModel
    77         {
    78             /// <summary>
    79             /// Gets or sets the error message.
    80             /// </summary>
    81             /// <value>
    82             /// The error message.
    83             /// </value>
    84             public string ErrorMessage { get; set; }
    85 
    86         }
    87 
    88     }
    89 }
    View Code

    然后在FilterConfig添加

    Global.asax全局下添加

     

    最后处理下ajax错误处理和服务器错误呈现形式

    @{
        ViewBag.Title = "General Site Error";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    <div class="container">
        <div class="row text-center">
            <br/>
            <br />
            <br />
            <br />
            <br />
            <div class="col-md-6 col-md-offset-3 text-center">
                @{
    
                    var exception = ViewData.Model;
                    var statusCode = exception == null ? 404 : 500;
                    Response.StatusCode = statusCode;
                    if (statusCode == 404)
                    {
                        <h1>404 Page not found!</h1>
                        <p>没有找到该网页!</p>
                    }
                    else if (statusCode == 500)
                    {
                        <h1>500 程序异常</h1>
                        <p>
                            <a class="btn" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
                                Error details
                            </a>
                        </p>
                        <div class="collapse" id="collapseExample">
                            <div class="card card-body">
                                <p style="text-align: left;">消息类型:@exception.GetType().Name<br />消息内容:@exception.Message <br />引发异常的方法:@exception.TargetSite <br />引发异常的对象:@exception.Source<br />错误详细记录:@exception.StackTrace</p>
                            </div>
                        </div>
    
                    }
                }
                <p style="font-size: 14px; color: Gray">请使用浏览器的后退功能已保证您填写的数据没有丢失!</p>
            </div>
        </div>
    
        <div class="row text-center">
            <div class="col-md-8 col-md-offset-2">
                <h3> <i class="fa fa-lightbulb-o fa-5x"></i> </h3>
                <a href="@Url.Action("Index","Home")" class="btn">GO TO HOME PAGE</a>
            </div>
        </div>
    
    </div>
     $(document).ajaxError(function (event, request, settings) {
                //request.responseText
                if (request.responseText != "") {
                    var jsonValue = jQuery.parseJSON(request.responseText);
                }
                toastr.error("<li>settings.url:" + settings.url + "</li>" + "<li>request.status:" + request.status + "</li>" + "<li>request.statusText:" + request.statusText + "</li>" + "<li>ErrorMessage:" + jsonValue.ErrorMessage + "</li>");
            });

     

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-12-22 11:06 , Processed in 0.057350 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表