DEV Community

MustafaSamedYeyin
MustafaSamedYeyin

Posted on

3 2

Asp.net core Handle Errors; UseDeveloperExceptionPage, UseExceptionHandler Giriş.

Model-view-controller uygulaması yaratalım :

Configure metodunu şimdi inceleyelim :

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Enter fullscreen mode Exit fullscreen mode

Şuraya dikkat edelim :

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
Enter fullscreen mode Exit fullscreen mode

burada diyoruz ki eğer Development oratmında isek UseDeveloperExceptionPage ile çıkan hataları görebiliyoruz.

Şimdi HomeController.cs'ye gidelim ve Index metodunda bir hata fırlatıp, davranışa bakalım :

        public IActionResult Index()
        {

            throw new Exception("Bu bizim hatamız.");
            return View();
        }
Enter fullscreen mode Exit fullscreen mode

uygulamayı çalıştıralım.

Image description

Gördüğünüz üzere developer'lara özel hata sayfasını görüldü.

Not: Developer'lara özel olan hata sayfalarını production ortamında göstermek büyük bir güvenlik açığıdır.

Şimdi launchsettings.json dan environment'ımızı Production'a alalım.

Aşağıdaki kodları inceleyelim :

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
Enter fullscreen mode Exit fullscreen mode

Artık environment'ımız development modunda olmadığından kod akışı else'in içinde olacaktır. UseExceptionHandler middleware'i ile hata yönetimi yapmaktayız.

Bunları anlaşıldıktan sonra uygulamayı çalıştıralım :

Image description

UseExceptionHandler("Home/Error") middleware'i bizi Home içindeki Error sayfamıza yönlendirdi bizi. Yani şuraya :

 [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
Enter fullscreen mode Exit fullscreen mode

Şimdi ise Error üstüne sağ tıklayıp "Go to View" diyelim :

Image description

Gördüğünüz üzere bize app.UseExceptionHandler("/Home/Error"); ifadesinin gösterdiği Error.cshtml çıktı:

Image description

Bu Error metodunun içinde istediğimiz loglamayı yapabiliriz ve Error.cshtml içerisinde istediğimiz hata mesajını gösteririz.

Bir dahaki yazımda hataları dosya'ya loglamayı göreceğiz.

En iyi dileklerim ile.

Mustafa Samed Yeyin.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More