我的一个Console application,有很多数据库操作,因为数据库过载的时候,会造成console的sqlexception 异常,使console崩溃。
我有不想对每个数据库操作都try catch。应该怎么样在console中设置一个全局异常处理,使console不再崩溃呢?
谢谢
http://www.tutorialspanel.com/create-a-global-error-handler-in-c-for-a-console-application/index.htm
using System;
class Program {
static void Main(string[] args) {
System.AppDomain.CurrentDomain.UnhandledException+=UnhandledExceptionTrapper;
throw new Exception("Global Exception Handler");
}
static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
Console.WriteLine(e.ExceptionObject.ToString());
Console.WriteLine("Press Enter to Exit");
Console.ReadLine();
Environment.Exit(0);
}
}
.NET Core 过滤器实现
public class GlobalExceptionFilter:Attribute, IExceptionFilter
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IModelMetadataProvider _modelMetadataProvider;
public GlobalExceptionFilter(
IHostingEnvironment hostingEnvironment,
IModelMetadataProvider modelMetadataProvider)
{
_hostingEnvironment = hostingEnvironment;
_modelMetadataProvider = modelMetadataProvider;
}
/// <summary>
/// 发生异常进入
/// </summary>
/// <param name="context"></param>
public async void OnException(ExceptionContext context)
{
ContentResult result = new ContentResult
{
StatusCode = 500,
ContentType = "text/json;charset=utf-8;"
};
if (_hostingEnvironment.IsDevelopment())
{
var json = new { message = context.Exception.Message };
result.Content = JsonConvert.SerializeObject(json);
}
else
{
result.Content = "抱歉,出错了";
}
context.Result = result;
context.ExceptionHandled = true;
}
}