如何在.NET Core中捕获异常并使用状态代码进行响应 [英] How to catch an exception and respond with a status code in .NET Core
问题描述
我正在运行.Net Core Web API项目。
我有一个启动文件(如下)。在 Startup.ConfigureServices(...)
方法中,我添加了一个创建IFoo实例的工厂方法。我想捕获IFooFactory引发的任何异常,并返回带有状态代码的更好的错误消息。目前,我收到了500错误和异常消息。有人可以帮忙吗?
I am running a .Net Core Web API project.
I have a startup file (below). In the Startup.ConfigureServices(...)
method, I add a factory method that creates an instance of IFoo. I want to catch any exceptions that the IFooFactory throws and return a better error message with a status code. At the moment I getting a 500 Error with the exception Message. Can anyone help?
public interface IFooFactory
{
IFoo Create();
}
public class FooFactory : IFooFactory
{
IFoo Create()
{
throw new Exception("Catch Me!");
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IFooFactory,FooFactory>();
services.AddScoped(serviceProvider => {
IFooFactory fooFactory = serviceProvider.GetService<IFooFactory>();
return fooFactory.Create(); // <== Throws Exception
});
}
}
推荐答案
所以当我以两种不同的方式阅读问题时,我发布了两个不同的答案-很多删除/取消删除/编辑-不确定哪个实际回答了您的问题:
So I've posted two different answers as I read the question in two different ways - lots of deleting/undeleting/editing - not sure which one actually answers your question:
要弄清楚应用程序启动时什么地方出了错并且根本无法正常工作,请尝试以下操作:
使用<$中的开发人员例外页面c $ c>启动:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
app.UseDeveloperExceptionPage();
}
在程序中
类:
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.CaptureStartupErrors(true) // useful for debugging
.UseSetting("detailedErrors", "true") // what it says on the tin
.Build();
host.Run();
}
如果您想在一般情况下使用api处理偶尔的异常然后可以使用一些中间件:
public class ExceptionsMiddleware
{
private readonly RequestDelegate _next;
/// <summary>
/// Handles exceptions
/// </summary>
/// <param name="next">The next piece of middleware after this one</param>
public ExceptionsMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary>
/// The method to run in the piepline
/// </summary>
/// <param name="context">The current context</param>
/// <returns>As task which is running the action</returns>
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
}
catch(Exception ex)
{
// Apply some logic based on the exception
// Maybe log it as well - you can use DI in
// the constructor to inject a logging service
context.Response.StatusCode = //Your choice of code
await context.Response.WriteAsync("Your message");
}
}
}
有一个'gotcha'这样-如果响应头已经发送,则无法编写状态代码。
您可以在<$中配置中间件c $ c>启动类,使用配置
方法:
You configure the middleware in the Startup
class using the Configure
method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
app.UseMiddleware<ExceptionsMiddleware>();
}
这篇关于如何在.NET Core中捕获异常并使用状态代码进行响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!