예제 #1
0
        public static void AddFluentConfigurations(this IServiceCollection services)
        {
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = (context) =>
                {
                    List <string> errors = context.ModelState.Values.SelectMany(x => x.Errors.Select(p => p.ErrorMessage)).ToList();

                    bool defaultResponse = false;
                    foreach (string item in errors)
                    {
                        if (string.IsNullOrEmpty(item))
                        {
                            defaultResponse = true;
                        }
                    }

                    if (defaultResponse)
                    {
                        errors.Clear();
                        foreach (Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateEntry item in context.ModelState.Values)
                        {
                            foreach (Microsoft.AspNetCore.Mvc.ModelBinding.ModelError i in item.Errors)
                            {
                                errors.Add(i.Exception.Message);
                            }
                        }
                    }


                    List <DomainNotification> errorList = new List <DomainNotification>();
                    foreach (var error in errors)
                    {
                        errorList.Add(new DomainNotification(error));
                    }

                    var result = new DefaultAPIResponse
                    {
                        Success       = false,
                        Data          = null,
                        Notifications = errorList
                    };

                    return(new BadRequestObjectResult(result));
                };
            });
        }
예제 #2
0
        public static void UseGlobalExceptionHandler(this IApplicationBuilder app,
                                                     ILoggerFactory loggerFactory)
        {
            app.UseExceptionHandler(builder =>
            {
                builder.Run(async context =>
                {
                    var exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>();

                    if (exceptionHandlerFeature != null)
                    {
                        var logger = loggerFactory.CreateLogger("GlobalExceptionHandler");
                        logger.LogError($"Failed to execute: {exceptionHandlerFeature.Error}");

                        context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
                        context.Response.ContentType = "application/json";
                        string path = Path.Combine($"{Directory.GetCurrentDirectory()}\\log\\{ DateTime.Now.ToString("MM-dd-yyyy") }-errors.txt");
                        string file = $@"Error: {DateTime.Now.ToString("dd/MM/yyyy")}{Environment.NewLine
                            }========================================================================================================================================={
                            Environment.NewLine}{exceptionHandlerFeature.Error}{Environment.NewLine
                            }_________________________________________________________________________________________________________________________________________{
                            Environment.NewLine}";

                        string currentContent = String.Empty;
                        if (File.Exists(path))
                        {
                            currentContent = File.ReadAllText(path);
                        }
                        File.WriteAllText(path, file + currentContent);

                        var json = new DefaultAPIResponse
                        {
                            Success       = false,
                            Data          = null,
                            Notifications = new List <DomainNotification> {
                                new DomainNotification("An error ocurred! See details.")
                            },
                        };

                        await context.Response.WriteAsync(JsonConvert.SerializeObject(json));
                    }
                });
            });
        }
예제 #3
0
 public BaseResponseController()
 {
     _response = new DefaultAPIResponse();
 }