简体   繁体   中英

How to remove app.UseExceptionHandler from the startup.cs in netcore to a other file?

I have a netcore application. And I want to remove the app.UseExceptionHandler method from the startup.cs to a separated class. So that the startup.cs class would be smaller.

So the whole method looks like this:


 // Only in development envirionment the hole stacktrace is returned.
            app.UseExceptionHandler(
                    options =>
                    {
                        options.Run(
                            async context =>
                            {
                                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                                context.Response.ContentType = "application/json";
                                var ex = context.Features.Get<IExceptionHandlerFeature>();
                                if (ex != null)
                                {
                                    ILogger logger = loggerFactory.CreateLogger("unhandled exception");
                                    logger.LogCritical(1, ex.Error, "unhandled exception");
                                    Dictionary<string, string> errorObject;

                                    if (appSettings.IsDebug) //TODO: change this to env.IsDevelopment() when envirionment is set on servers?
                                    {
                                        errorObject = new Dictionary<string, string>
                                        {
                                            {"message" , ex.Error.Message },
                                            {"stackTrace", ex.Error.StackTrace },
                                            {"source", ex.Error.Source}
                                        };
                                    }
                                    else
                                    {
                                        // Do not show any information in production envirionment.
                                        errorObject = new Dictionary<string, string>
                                        {
                                            { "message" , "An error occurred!" }
                                        };
                                    }

                                    await context.Response.WriteAsync(JsonConvert.SerializeObject(errorObject)).ConfigureAwait(false);
                                }
                            });
                    }
            );

And so I made a class:

public class ErrorHandlingMiddleware
    {


        public static IServiceCollection HanldeErrors()
        {

            app.UseExceptionHandler(
                       options =>
                        {
                            options.Run(
                                async context =>
                                {
                                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                                    context.Response.ContentType = "application/json";
                                    var ex = context.Features.Get<IExceptionHandlerFeature>();
                                    if (ex != null)
                                    {
                                        ILogger logger = loggerFactory.CreateLogger("unhandled exception");
                                        logger.LogCritical(1, ex.Error, "unhandled exception");
                                        Dictionary<string, string> errorObject;

                                        if (appSettings.IsDebug) //TODO: change this to env.IsDevelopment() when envirionment is set on servers?
                                    {
                                            errorObject = new Dictionary<string, string>
                                            {
                                            {"message" , ex.Error.Message
    },
                                            {"stackTrace", ex.Error.StackTrace
},
                                            {"source", ex.Error.Source}
                                            };
                                        }
                                        else
                                        {
                                        // Do not show any information in production envirionment.
                                        errorObject = new Dictionary<string, string>
                                            {
                                            { "message" , "An error occurred!" }
                                            };
                                        }

                                        await context.Response.WriteAsync(JsonConvert.SerializeObject(errorObject)).ConfigureAwait(false);
                                    }
                                });
                        }
                );



        }
    }

But I don't know what I have to change about this class? And how I have to customize it?

oke, I have it now like this:

 public static class ErrorHandlingMiddleware
    {

        public static void  HanldeErrors(IApplicationBuilder app, ILoggerFactory loggerFactory, IOptions<AppSettings> appSettingsOptions)
        {

            var appSettings = appSettingsOptions.Value;

            app.UseExceptionHandler(
                       options =>
                        {
                            options.Run(
                                async context =>
                                {
                                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                                    context.Response.ContentType = "application/json";
                                    var ex = context.Features.Get<IExceptionHandlerFeature>();
                                    if (ex != null)
                                    {
                                        ILogger logger = loggerFactory.CreateLogger("unhandled exception");
                                        logger.LogCritical(1, ex.Error, "unhandled exception");
                                        Dictionary<string, string> errorObject;

                                        if (appSettings.IsDebug) //TODO: change this to env.IsDevelopment() when envirionment is set on servers?
                                    {
                                            errorObject = new Dictionary<string, string>
                                            {
                                            {"message" , ex.Error.Message
    },
                                            {"stackTrace", ex.Error.StackTrace
},
                                            {"source", ex.Error.Source}
                                            };
                                        }
                                        else
                                        {
                                        // Do not show any information in production envirionment.
                                        errorObject = new Dictionary<string, string>
                                            {
                                            { "message" , "An error occurred!" }
                                            };
                                        }

                                        await context.Response.WriteAsync(JsonConvert.SerializeObject(errorObject)).ConfigureAwait(false);
                                    }
                                });
                        }
                );
        }
    }

And my startup.cs looks like this?


   public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<AppSettings> appSettingsOptions)
{


            app.UseMiddleware(typeof(ErrorHandlingMiddleware));

            app.UseStaticFiles();

}

But is this the correct way?

Thank you

The posted code doesn't create a middleware class, it simply extracted the method to a separate static class. There's no need to register that class as middleware - in fact it's not possible as it doesn't implement IMiddleWare .

This static method can be converted to an extension method too, by adding this to the first parameter :

public static void  HanldeErrors(this IApplicationBuilder app, ILoggerFactory loggerFactory, IOptions<AppSettings> appSettingsOptions)

The method should be called instead of UseExceptionHandler , eg:

 HanldeErrors(app,loggerFactory, appSettingsOptions);

Or

 app.HanldeErrors(loggerFactory, appSettingsOptions);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM