使用 appdomain.currentdomain.unhandledexception 只需订阅该事件并在事件处理程序中编写异常处理逻辑,如记录日志、清理资源并调用 environment.exit 优雅退出;2. try-catch 用于处理可预测的局部异常,而 unhandledexception 作为全局防线捕获未被处理的异常,二者应结合使用,不可相互替代;3. 在 asp.net core 中应使用异常处理中间件实现全局异常处理,通过在请求管道中捕获异常并返回统一响应,相比 appdomain 事件,中间件更契合 web 应用且支持细粒度控制和良好集成。

AppDomain.CurrentDomain.UnhandledException 提供了一种捕获应用程序级别未处理异常的机制,是构建健壮应用程序的重要一环。它允许你在应用程序崩溃前记录错误信息、清理资源,甚至尝试恢复,从而提升用户体验和减少潜在损失。
全局异常处理
使用
AppDomain.CurrentDomain.UnhandledException
using System;
namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(GlobalExceptionHandler);
            // 模拟一个未处理的异常
            throw new Exception("这是一个未处理的异常!");
            Console.WriteLine("这行代码不会被执行"); // 因为异常已经抛出
        }
        static void GlobalExceptionHandler(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;
            Console.WriteLine("全局异常处理程序捕获到异常:");
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
            // 在这里可以进行日志记录、资源清理等操作
            // 阻止应用程序终止 (不推荐,除非你知道自己在做什么)
            // e.IsTerminating = false;
            // 强制退出应用程序
            Environment.Exit(1);
        }
    }
}这段代码展示了如何订阅
UnhandledException
GlobalExceptionHandler
e.IsTerminating
false
try-catch
AppDomain.CurrentDomain.UnhandledException
try-catch
简单来说,
try-catch
UnhandledException
try-catch
try-catch
FileNotFoundException
IOException
UnhandledException
try-catch
记住,
UnhandledException
try-catch
try-catch
UnhandledException
在 ASP.NET Core 中,实现全局异常处理的方式与传统的 ASP.NET 不同,因为它依赖于中间件管道。 你不能直接使用
AppDomain.CurrentDomain.UnhandledException
ASP.NET Core 提供了几种实现全局异常处理的方法,最常见的是使用异常处理中间件。 你可以创建一个自定义的中间件来捕获所有未处理的异常,并执行相应的操作,例如记录错误信息、返回友好的错误页面等。
一个简单的异常处理中间件可能如下所示:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Net;
using System.Threading.Tasks;
namespace MyApp.Middleware
{
    public class ExceptionHandlerMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionHandlerMiddleware> _logger;
        public ExceptionHandlerMiddleware(RequestDelegate next, ILogger<ExceptionHandlerMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An unhandled exception occurred.");
                await HandleExceptionAsync(context, ex);
            }
        }
        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            // 返回自定义错误信息
            await context.Response.WriteAsync(new
            {
                StatusCode = context.Response.StatusCode,
                Message = "An unexpected error occurred. Please try again later."
            }.ToString());
        }
    }
    public static class ExceptionHandlerMiddlewareExtensions
    {
        public static IApplicationBuilder UseExceptionHandlerMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ExceptionHandlerMiddleware>();
        }
    }
}然后在
Startup.cs
Configure
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ... 其他中间件配置
    app.UseExceptionHandlerMiddleware(); // 注册自定义异常处理中间件
    // ... 其他中间件配置
}关键区别在于:
AppDomain.CurrentDomain.UnhandledException
总而言之,在 ASP.NET Core 中,使用异常处理中间件是实现全局异常处理的首选方法。
以上就是AppDomain.CurrentDomain.UnhandledException有什么用?全局异常处理的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                
                                
                                
                                
                                
                                
                                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号