• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

.net core异常中间件的使用

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

正文

if (env.IsDevelopment())
{
	app.UseDeveloperExceptionPage();
}

这样写入中间件哈,那么在env环境下就会去执行UseDeveloperExceptionPage。

public static IApplicationBuilder UseDeveloperExceptionPage(this IApplicationBuilder app)
{
	if (app == null)
	{
		throw new ArgumentNullException(nameof(app));
	}

	return app.UseMiddleware<DeveloperExceptionPageMiddleware>();
}

那么我们应该去看DeveloperExceptionPageMiddleware中间件哈。

那么这里介绍它是如何能够捕获其他中间件的异常的哈。

里面的invoke:

其实它的操作是很简单的,直接在外面套了try catch。

里面的异常处理怎么处理的可以直接去看DeveloperExceptionPageMiddleware 中间件,里面的操作也比较简单处理。

测试:

[HttpGet]
public int GetService([FromServices]ISelfService selfService)
{
	throw new System.Exception("错误");
	return 1;
}

结果:

因为上面说了,这个是dev环境下,那么生产环境不能直接给用户看到错误信息。

正式环境:

app.UseExceptionHandler("/error");

将错误转移到/error 处理。具体UseExceptionHandler细节篇里面介绍,有许多可以借鉴的地方。

[ApiController]
[Route("[controller]")]
public class ErrorController : Controller
{
	public ILogger<ErrorController> _logger;
	public ErrorController(ILogger<ErrorController> logger)
	{
		this._logger = logger;
	}

	public IActionResult Index()
	{
		var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

		var ex = exceptionHandlerPathFeature?.Error;

		var knownException = ex as IKnownException;

		if (knownException == null)
		{
			_logger.LogError(ex, ex.Message);
			knownException = KnownException.Unknow;
		}
		else
		{
			knownException = KnownException.FromKnowException(knowException);
		}

		return View(knownException);
	}
}

视图:

<html>
<head>

</head>
<body>
<div>
    错误码: @Model.ErrorCode
</div>
<div>
    错误信息: @Model.Message
</div>
</body>
</html>

IKnownException:

public interface IKnownException
{
	public string Message { get; }

	public int ErrorCode { get; }

	public object[] ErrorData { get; }
}

KnownException:

public class KnownException : IKnownException
{
	public string Message
	{
		get; private set;
	}

	public int ErrorCode
	{
		get; private set;
	}

	public object[] ErrorData
	{
		get;
		private set;
	}

	public readonly static IKnownException Unknow = new KnownException { Message = "未知错误", ErrorCode = 99 };

	public static IKnownException FromKnowException(IKnownException Exception)
	{
		return new KnownException{Message = Exception.Message, ErrorCode = Exception.ErrorCode, ErrorData = Exception.ErrorData};
	}
}

测试1:

[HttpGet]
public int GetService([FromServices]ISelfService selfService)
{
	throw new System.Exception("错误");
	return 1;
}

这种属于未知异常,结果:

现在弄一个支付异常:

public class PayErrorException : Exception, IKnownException
{
	public PayErrorException(string message, int errorCode, params object[] errorData): base(message)
	{
		this.ErrorCode = errorCode;
		this.ErrorData = errorData;
	}

	public int ErrorCode { get;private set; }

	public object[] ErrorData { get;private set; }
}

测试2:

[HttpGet]
public int GetService([FromServices]ISelfService selfService)
{

	throw new PayErrorException("支付错误",405,null);
	return 1;
}

将异常处理放入到中间件分支中。

app.UseExceptionHandler(errApp =>
{
	errApp.Run(async context =>
	{
		var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
		IKnownException knownException = exceptionHandlerPathFeature.Error as IKnownException;
		if (knownException == null)
		{
			var logger = context.RequestServices.GetService<ILogger<MyExceptionFilterAttribute>>();
			logger.LogError(exceptionHandlerPathFeature.Error, exceptionHandlerPathFeature.Error.Message);
			knownException = KnownException.Unknown;
			context.Response.StatusCode = StatusCodes.Status500InternalServerError;
		}
		else
		{
			knownException = KnownException.FromKnownException(knownException);
			context.Response.StatusCode = StatusCodes.Status200OK;
		}
		var jsonOptions = context.RequestServices.GetService<IOptions<JsonOptions>>();
		context.Response.ContentType = "application/json; charset=utf-8";
		await context.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(knownException, jsonOptions.Value.JsonSerializerOptions));
	});
});

效果一样就不演示了。如果是已知异常错误码应该为200,一个是500异常是系统无法处理,系统错误,但是已知错误是属于系统正常处理。另一个是监控系统,认为报500错误,是会持续放出系统警告。

还有一种局部异常,只在mvc中生效,而不是全局生效:

public class MyExceptionFilter : IExceptionFilter
{
	public void OnException(ExceptionContext context)
	{
		IKnownException knownException = context.Exception as IKnownException;
		if (knownException == null)
		{
			var logger = context.HttpContext.RequestServices.GetService<ILogger<MyExceptionFilterAttribute>>();
			logger.LogError(context.Exception, context.Exception.Message);
			knownException = KnownException.Unknown;
			context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
		}
		else
		{
			knownException = KnownException.FromKnownException(knownException);
			context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
		}
		context.Result = new JsonResult(knownException)
		{
			ContentType = "application/json; charset=utf-8"
		};
	}
}

在mvc 中注册:

services.AddMvc(mvcOptions =>
{
	mvcOptions.Filters.Add<MyExceptionFilter>();
}).AddJsonOptions(jsonOptions =>
{
	jsonOptions.JsonSerializerOptions.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
});

最后介绍一种,只作用于某个控制器,或者action:

public class MyExceptionFilterAttribute : ExceptionFilterAttribute
{
	public override void OnException(ExceptionContext context)
	{
		IKnownException knownException = context.Exception as IKnownException;
		if (knownException == null)
		{
			var logger = context.HttpContext.RequestServices.GetService<ILogger<MyExceptionFilterAttribute>>();
			logger.LogError(context.Exception, context.Exception.Message);
			knownException = KnownException.Unknown;
			context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
		}
		else
		{
			knownException = KnownException.FromKnownException(knownException);
			context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
		}
		context.Result = new JsonResult(knownException)
		{
			ContentType = "application/json; charset=utf-8"
		};
	}
}

查看一下ExceptionFilterAttribute头部:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public abstract class ExceptionFilterAttribute : Attribute, IAsyncExceptionFilter, IExceptionFilter, IOrderedFilter

上面标志了可以放于类上也可以放于方法上。所以可以放至在controller上,也可以action上,看需求了。


以上就是.net core异常中间件的使用的详细内容,更多关于.net core异常中间件的资料请关注极客世界其它相关文章!


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
.Net基于Thread实现自旋锁的三种方式发布时间:2022-02-05
下一篇:
.net core静态中间件的使用发布时间:2022-02-05
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap