Saturday, 18 January 2020

Asp.Net Core WebAPI Global exception handler [Code help]


Developer exception page is useful only for development environment, we can not show it in production environment, also it's not helpful in case of Web-Api.
So, we can create a controller for global error handling,and we can configure it using ExceptionHandler middle-ware like:

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}
            app.UseExceptionHandler("/Error");
            app.UseMvc();
}
we can create controller and action methods like below :


    public class ErrorController : Controller
    {
        private readonly IConfiguration config;

        public ErrorController(IConfiguration config)
        {
            this.config = config; // with the help of Iconfiguration we can access appSetting here.
        }
        
        [Route("/Error")]
        public ActionResult Get([FromServices] IHostingEnvironment webHostEnvironment)
        {
            var feature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
            var ex = feature?.Error;
            var isDev = webHostEnvironment.IsDevelopment();
            var problemDetails = new ProblemDetails
            {
                Status = (int)HttpStatusCode.InternalServerError,
                Instance = feature?.Path,
                Title = isDev ? $"{ex.GetType().Name}: {ex.Message}" : "An error occurred.",
                Detail = isDev ? ex.StackTrace : null,
            };

            return StatusCode(problemDetails.Status.Value, problemDetails);

            //:Other-way to return errors in json format
            var feature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
            return Json(new
            {
                StatusCode = 500,
                ContentType = "Application/json",
                SerializerSettings = "",
                Value = feature.Error.Message
            });
        }

    }

How to create and use middleware in asp.net core

Middleware is piece of code that's assembled into an app pipeline to handle requests and responses.  Each middleware component in the re...