From 8b3f81a22726db22e27582e2f45769994a3e1319 Mon Sep 17 00:00:00 2001 From: Marinko Date: Fri, 20 Jul 2018 19:26:59 +0200 Subject: [PATCH 01/10] Global error handling end project --- .../GlobalErrorHandling.sln | 0 .../Controllers/ValuesController.cs | 32 +++++++++++++ .../ExceptionMiddleware.cs | 46 +++++++++++++++++++ .../GlobalErrorHandling/DataManager.cs | 0 .../ExceptionMiddlewareExtensions.cs | 42 +++++++++++++++++ .../GlobalErrorHandling.csproj | 0 .../GlobalErrorHandling.csproj.user | 0 .../Models/ErrorDetails.cs | 16 +++++++ .../GlobalErrorHandling/Models/Student.cs | 0 .../GlobalErrorHandling/Program.cs | 0 .../Properties/launchSettings.json | 0 .../GlobalErrorHandling/Startup.cs | 6 ++- .../appsettings.Development.json | 0 .../GlobalErrorHandling/appsettings.json | 0 .../GlobalErrorHandling/nlog.config | 0 .../LoggerService/ILoggerManager.cs | 0 .../LoggerService/LoggerManager.cs | 0 .../LoggerService/LoggerService.csproj | 0 .../Controllers/ValuesController.cs | 26 ----------- README.md | 2 +- 20 files changed, 142 insertions(+), 28 deletions(-) rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/GlobalErrorHandling.sln (100%) create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/GlobalErrorHandling/DataManager.cs (100%) create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/GlobalErrorHandling/GlobalErrorHandling.csproj (100%) rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/GlobalErrorHandling/GlobalErrorHandling.csproj.user (100%) create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/GlobalErrorHandling/Models/Student.cs (100%) rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/GlobalErrorHandling/Program.cs (100%) rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/GlobalErrorHandling/Properties/launchSettings.json (100%) rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/GlobalErrorHandling/Startup.cs (86%) rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/GlobalErrorHandling/appsettings.Development.json (100%) rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/GlobalErrorHandling/appsettings.json (100%) rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/GlobalErrorHandling/nlog.config (100%) rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/LoggerService/ILoggerManager.cs (100%) rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/LoggerService/LoggerManager.cs (100%) rename {GlobalErrorHandling-Start => GlobalErrorHandling-End}/LoggerService/LoggerService.csproj (100%) delete mode 100644 GlobalErrorHandling-Start/GlobalErrorHandling/Controllers/ValuesController.cs diff --git a/GlobalErrorHandling-Start/GlobalErrorHandling.sln b/GlobalErrorHandling-End/GlobalErrorHandling.sln similarity index 100% rename from GlobalErrorHandling-Start/GlobalErrorHandling.sln rename to GlobalErrorHandling-End/GlobalErrorHandling.sln diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs new file mode 100644 index 0000000..ad5fb42 --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs @@ -0,0 +1,32 @@ +using System; +using LoggerService; +using Microsoft.AspNetCore.Mvc; + +namespace GlobalErrorHandling.Controllers +{ + [Route("api/[controller]")] + public class ValuesController : Controller + { + private ILoggerManager _logger; + + public ValuesController(ILoggerManager logger) + { + _logger = logger; + } + + [HttpGet] + public IActionResult Get() + { + + _logger.LogInfo("Fetching all the Students from the storage"); + + var students = DataManager.GetAllStudents(); //simulation for the data base access + + throw new Exception("Exception while fetching all the students from the storage."); + + _logger.LogInfo($"Returning {students.Count} students."); + + return Ok(students); + } + } +} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs b/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs new file mode 100644 index 0000000..f579520 --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs @@ -0,0 +1,46 @@ +using GlobalErrorHandling.Models; +using LoggerService; +using Microsoft.AspNetCore.Http; +using System; +using System.Net; +using System.Threading.Tasks; + +namespace GlobalErrorHandling.CustomExceptionMiddleware +{ + public class ExceptionMiddleware + { + private readonly RequestDelegate _next; + private readonly ILoggerManager _logger; + + public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger) + { + _logger = logger; + _next = next; + } + + public async Task InvokeAsync(HttpContext httpContext) + { + try + { + await _next(httpContext); + } + catch (Exception ex) + { + _logger.LogError($"Something went wrong: {ex}"); + await HandleExceptionAsync(httpContext, ex); + } + } + + private static Task HandleExceptionAsync(HttpContext context, Exception exception) + { + context.Response.ContentType = "application/json"; + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + + return context.Response.WriteAsync(new ErrorDetails() + { + StatusCode = context.Response.StatusCode, + Message = "Internal Server Error from the custom middleware." + }.ToString()); + } + } +} diff --git a/GlobalErrorHandling-Start/GlobalErrorHandling/DataManager.cs b/GlobalErrorHandling-End/GlobalErrorHandling/DataManager.cs similarity index 100% rename from GlobalErrorHandling-Start/GlobalErrorHandling/DataManager.cs rename to GlobalErrorHandling-End/GlobalErrorHandling/DataManager.cs diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs new file mode 100644 index 0000000..0480604 --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs @@ -0,0 +1,42 @@ +using GlobalErrorHandling.CustomExceptionMiddleware; +using GlobalErrorHandling.Models; +using LoggerService; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics; +using Microsoft.AspNetCore.Http; +using System.Net; + +namespace GlobalErrorHandling.Extensions +{ + public static class ExceptionMiddlewareExtensions + { + public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILoggerManager logger) + { + app.UseExceptionHandler(appError => + { + appError.Run(async context => + { + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + context.Response.ContentType = "application/json"; + + var contextFeature = context.Features.Get(); + if(contextFeature != null) + { + logger.LogError($"Something went wrong: {contextFeature.Error}"); + + await context.Response.WriteAsync(new ErrorDetails() + { + StatusCode = context.Response.StatusCode, + Message = "Internal Server Error." + }.ToString()); + } + }); + }); + } + + public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app) + { + app.UseMiddleware(); + } + } +} diff --git a/GlobalErrorHandling-Start/GlobalErrorHandling/GlobalErrorHandling.csproj b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj similarity index 100% rename from GlobalErrorHandling-Start/GlobalErrorHandling/GlobalErrorHandling.csproj rename to GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj diff --git a/GlobalErrorHandling-Start/GlobalErrorHandling/GlobalErrorHandling.csproj.user b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user similarity index 100% rename from GlobalErrorHandling-Start/GlobalErrorHandling/GlobalErrorHandling.csproj.user rename to GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs new file mode 100644 index 0000000..9830a5c --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs @@ -0,0 +1,16 @@ +using Newtonsoft.Json; + +namespace GlobalErrorHandling.Models +{ + public class ErrorDetails + { + public int StatusCode { get; set; } + public string Message { get; set; } + + + public override string ToString() + { + return JsonConvert.SerializeObject(this); + } + } +} diff --git a/GlobalErrorHandling-Start/GlobalErrorHandling/Models/Student.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs similarity index 100% rename from GlobalErrorHandling-Start/GlobalErrorHandling/Models/Student.cs rename to GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs diff --git a/GlobalErrorHandling-Start/GlobalErrorHandling/Program.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Program.cs similarity index 100% rename from GlobalErrorHandling-Start/GlobalErrorHandling/Program.cs rename to GlobalErrorHandling-End/GlobalErrorHandling/Program.cs diff --git a/GlobalErrorHandling-Start/GlobalErrorHandling/Properties/launchSettings.json b/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json similarity index 100% rename from GlobalErrorHandling-Start/GlobalErrorHandling/Properties/launchSettings.json rename to GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json diff --git a/GlobalErrorHandling-Start/GlobalErrorHandling/Startup.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs similarity index 86% rename from GlobalErrorHandling-Start/GlobalErrorHandling/Startup.cs rename to GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs index 2c626ad..2b12794 100644 --- a/GlobalErrorHandling-Start/GlobalErrorHandling/Startup.cs +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NLog; +using GlobalErrorHandling.Extensions; namespace GlobalErrorHandling { @@ -27,13 +28,16 @@ public void ConfigureServices(IServiceCollection services) } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env) + public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerManager logger) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } + //app.ConfigureExceptionHandler(logger); + app.ConfigureCustomExceptionMiddleware(); + app.UseMvc(); } } diff --git a/GlobalErrorHandling-Start/GlobalErrorHandling/appsettings.Development.json b/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.Development.json similarity index 100% rename from GlobalErrorHandling-Start/GlobalErrorHandling/appsettings.Development.json rename to GlobalErrorHandling-End/GlobalErrorHandling/appsettings.Development.json diff --git a/GlobalErrorHandling-Start/GlobalErrorHandling/appsettings.json b/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json similarity index 100% rename from GlobalErrorHandling-Start/GlobalErrorHandling/appsettings.json rename to GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json diff --git a/GlobalErrorHandling-Start/GlobalErrorHandling/nlog.config b/GlobalErrorHandling-End/GlobalErrorHandling/nlog.config similarity index 100% rename from GlobalErrorHandling-Start/GlobalErrorHandling/nlog.config rename to GlobalErrorHandling-End/GlobalErrorHandling/nlog.config diff --git a/GlobalErrorHandling-Start/LoggerService/ILoggerManager.cs b/GlobalErrorHandling-End/LoggerService/ILoggerManager.cs similarity index 100% rename from GlobalErrorHandling-Start/LoggerService/ILoggerManager.cs rename to GlobalErrorHandling-End/LoggerService/ILoggerManager.cs diff --git a/GlobalErrorHandling-Start/LoggerService/LoggerManager.cs b/GlobalErrorHandling-End/LoggerService/LoggerManager.cs similarity index 100% rename from GlobalErrorHandling-Start/LoggerService/LoggerManager.cs rename to GlobalErrorHandling-End/LoggerService/LoggerManager.cs diff --git a/GlobalErrorHandling-Start/LoggerService/LoggerService.csproj b/GlobalErrorHandling-End/LoggerService/LoggerService.csproj similarity index 100% rename from GlobalErrorHandling-Start/LoggerService/LoggerService.csproj rename to GlobalErrorHandling-End/LoggerService/LoggerService.csproj diff --git a/GlobalErrorHandling-Start/GlobalErrorHandling/Controllers/ValuesController.cs b/GlobalErrorHandling-Start/GlobalErrorHandling/Controllers/ValuesController.cs deleted file mode 100644 index c466c31..0000000 --- a/GlobalErrorHandling-Start/GlobalErrorHandling/Controllers/ValuesController.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using LoggerService; -using Microsoft.AspNetCore.Mvc; - -namespace GlobalErrorHandling.Controllers -{ - [Route("api/[controller]")] - public class ValuesController : Controller - { - private ILoggerManager _logger; - - public ValuesController(ILoggerManager logger) - { - _logger = logger; - } - - [HttpGet] - public IEnumerable Get() - { - return new string[] { "value1", "value2" }; - } - } -} diff --git a/README.md b/README.md index a18f5b1..d9c58fc 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ -# global-error-handling-aspnetcore -start +# global-error-handling-aspnetcore - end https://code-maze.com/global-error-handling-dotnetcore/ \ No newline at end of file From 041a290171425c05cbd9405911acc7cc62d66370 Mon Sep 17 00:00:00 2001 From: Code Maze Date: Mon, 23 Jul 2018 06:26:38 +0200 Subject: [PATCH 02/10] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d9c58fc..4faa1d2 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ -# global-error-handling-aspnetcore - end +# Global Error Handling in ASP.NET Core Web API - END -https://code-maze.com/global-error-handling-dotnetcore/ \ No newline at end of file +https://code-maze.com/global-error-handling-aspnetcore/ From 60f1a89aa2590a168b9006919efc9c57e2aa414c Mon Sep 17 00:00:00 2001 From: MarinkoSpasojevic <36244468+MarinkoSpasojevic@users.noreply.github.com> Date: Mon, 22 Oct 2018 10:42:08 +0200 Subject: [PATCH 03/10] Update nlog.config --- GlobalErrorHandling-End/GlobalErrorHandling/nlog.config | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/nlog.config b/GlobalErrorHandling-End/GlobalErrorHandling/nlog.config index f31c804..9d888c8 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/nlog.config +++ b/GlobalErrorHandling-End/GlobalErrorHandling/nlog.config @@ -5,10 +5,6 @@ internalLogLevel="Trace" internalLogFile="c:/GlobalErrorHandlingLogs/internal_logs/internallog.txt"> - - - - - \ No newline at end of file + From ee8f5f3548156d5975d5f8ab5a7e9ff780511c92 Mon Sep 17 00:00:00 2001 From: Marinko Date: Mon, 18 Feb 2019 20:11:43 +0100 Subject: [PATCH 04/10] Removed old .net core version --- .../GlobalErrorHandling.sln | 31 ------------- .../Controllers/ValuesController.cs | 32 ------------- .../ExceptionMiddleware.cs | 46 ------------------- .../GlobalErrorHandling/DataManager.cs | 22 --------- .../ExceptionMiddlewareExtensions.cs | 42 ----------------- .../GlobalErrorHandling.csproj | 23 ---------- .../GlobalErrorHandling.csproj.user | 9 ---- .../Models/ErrorDetails.cs | 16 ------- .../GlobalErrorHandling/Models/Student.cs | 15 ------ .../GlobalErrorHandling/Program.cs | 25 ---------- .../Properties/launchSettings.json | 29 ------------ .../GlobalErrorHandling/Startup.cs | 44 ------------------ .../appsettings.Development.json | 10 ---- .../GlobalErrorHandling/appsettings.json | 15 ------ .../GlobalErrorHandling/nlog.config | 17 ------- .../LoggerService/ILoggerManager.cs | 14 ------ .../LoggerService/LoggerManager.cs | 34 -------------- .../LoggerService/LoggerService.csproj | 11 ----- 18 files changed, 435 deletions(-) delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling.sln delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/DataManager.cs delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Program.cs delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/appsettings.Development.json delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json delete mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/nlog.config delete mode 100644 GlobalErrorHandling-End/LoggerService/ILoggerManager.cs delete mode 100644 GlobalErrorHandling-End/LoggerService/LoggerManager.cs delete mode 100644 GlobalErrorHandling-End/LoggerService/LoggerService.csproj diff --git a/GlobalErrorHandling-End/GlobalErrorHandling.sln b/GlobalErrorHandling-End/GlobalErrorHandling.sln deleted file mode 100644 index 96c425f..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27703.2018 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GlobalErrorHandling", "GlobalErrorHandling\GlobalErrorHandling.csproj", "{EE171A5A-17A3-4C16-8A1B-5E72A33DA4E4}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LoggerService", "LoggerService\LoggerService.csproj", "{57214E50-4D1C-463A-A200-1EA829DE8BBE}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {EE171A5A-17A3-4C16-8A1B-5E72A33DA4E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EE171A5A-17A3-4C16-8A1B-5E72A33DA4E4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EE171A5A-17A3-4C16-8A1B-5E72A33DA4E4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EE171A5A-17A3-4C16-8A1B-5E72A33DA4E4}.Release|Any CPU.Build.0 = Release|Any CPU - {57214E50-4D1C-463A-A200-1EA829DE8BBE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {57214E50-4D1C-463A-A200-1EA829DE8BBE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {57214E50-4D1C-463A-A200-1EA829DE8BBE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {57214E50-4D1C-463A-A200-1EA829DE8BBE}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {E5D03030-7E40-4C80-8768-44A70842D9B1} - EndGlobalSection -EndGlobal diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs deleted file mode 100644 index ad5fb42..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using LoggerService; -using Microsoft.AspNetCore.Mvc; - -namespace GlobalErrorHandling.Controllers -{ - [Route("api/[controller]")] - public class ValuesController : Controller - { - private ILoggerManager _logger; - - public ValuesController(ILoggerManager logger) - { - _logger = logger; - } - - [HttpGet] - public IActionResult Get() - { - - _logger.LogInfo("Fetching all the Students from the storage"); - - var students = DataManager.GetAllStudents(); //simulation for the data base access - - throw new Exception("Exception while fetching all the students from the storage."); - - _logger.LogInfo($"Returning {students.Count} students."); - - return Ok(students); - } - } -} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs b/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs deleted file mode 100644 index f579520..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs +++ /dev/null @@ -1,46 +0,0 @@ -using GlobalErrorHandling.Models; -using LoggerService; -using Microsoft.AspNetCore.Http; -using System; -using System.Net; -using System.Threading.Tasks; - -namespace GlobalErrorHandling.CustomExceptionMiddleware -{ - public class ExceptionMiddleware - { - private readonly RequestDelegate _next; - private readonly ILoggerManager _logger; - - public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger) - { - _logger = logger; - _next = next; - } - - public async Task InvokeAsync(HttpContext httpContext) - { - try - { - await _next(httpContext); - } - catch (Exception ex) - { - _logger.LogError($"Something went wrong: {ex}"); - await HandleExceptionAsync(httpContext, ex); - } - } - - private static Task HandleExceptionAsync(HttpContext context, Exception exception) - { - context.Response.ContentType = "application/json"; - context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; - - return context.Response.WriteAsync(new ErrorDetails() - { - StatusCode = context.Response.StatusCode, - Message = "Internal Server Error from the custom middleware." - }.ToString()); - } - } -} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/DataManager.cs b/GlobalErrorHandling-End/GlobalErrorHandling/DataManager.cs deleted file mode 100644 index 408b43c..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/DataManager.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using GlobalErrorHandling.Models; - -namespace GlobalErrorHandling -{ - public static class DataManager - { - public static List GetAllStudents() - { - return new List - { - new Student { Name="Joe", LastName="Doe", Age=35, Gender="Male"}, - new Student { Name="Jane", LastName="Doe", Age=25, Gender="Female"}, - new Student { Name="Mick", LastName="Simon", Age=32, Gender="Male"}, - new Student { Name="Sandra", LastName="Summer", Age=30, Gender="Female"}, - }; - } - } -} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs deleted file mode 100644 index 0480604..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs +++ /dev/null @@ -1,42 +0,0 @@ -using GlobalErrorHandling.CustomExceptionMiddleware; -using GlobalErrorHandling.Models; -using LoggerService; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Diagnostics; -using Microsoft.AspNetCore.Http; -using System.Net; - -namespace GlobalErrorHandling.Extensions -{ - public static class ExceptionMiddlewareExtensions - { - public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILoggerManager logger) - { - app.UseExceptionHandler(appError => - { - appError.Run(async context => - { - context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; - context.Response.ContentType = "application/json"; - - var contextFeature = context.Features.Get(); - if(contextFeature != null) - { - logger.LogError($"Something went wrong: {contextFeature.Error}"); - - await context.Response.WriteAsync(new ErrorDetails() - { - StatusCode = context.Response.StatusCode, - Message = "Internal Server Error." - }.ToString()); - } - }); - }); - } - - public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app) - { - app.UseMiddleware(); - } - } -} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj deleted file mode 100644 index 57bfdc1..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj +++ /dev/null @@ -1,23 +0,0 @@ - - - - netcoreapp2.0 - - - - - - - - - - - - - - - - - - - diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user deleted file mode 100644 index 0776e7f..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user +++ /dev/null @@ -1,9 +0,0 @@ - - - - ProjectDebugger - - - GlobalErrorHandling - - \ No newline at end of file diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs deleted file mode 100644 index 9830a5c..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Newtonsoft.Json; - -namespace GlobalErrorHandling.Models -{ - public class ErrorDetails - { - public int StatusCode { get; set; } - public string Message { get; set; } - - - public override string ToString() - { - return JsonConvert.SerializeObject(this); - } - } -} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs deleted file mode 100644 index 5be9144..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace GlobalErrorHandling.Models -{ - public class Student - { - public string Name { get; set; } - public string LastName { get; set; } - public int Age { get; set; } - public string Gender { get; set; } - } -} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Program.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Program.cs deleted file mode 100644 index 0290050..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Program.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; - -namespace GlobalErrorHandling -{ - public class Program - { - public static void Main(string[] args) - { - BuildWebHost(args).Run(); - } - - public static IWebHost BuildWebHost(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup() - .Build(); - } -} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json b/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json deleted file mode 100644 index a332b15..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:55760/", - "sslPort": 0 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": false, - "launchUrl": "api/values", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "GlobalErrorHandling": { - "commandName": "Project", - "launchBrowser": false, - "launchUrl": "api/values", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "http://localhost:55761/" - } - } -} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs deleted file mode 100644 index 2b12794..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.IO; -using LoggerService; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using NLog; -using GlobalErrorHandling.Extensions; - -namespace GlobalErrorHandling -{ - public class Startup - { - public Startup(IConfiguration configuration) - { - LogManager.LoadConfiguration(String.Concat(Directory.GetCurrentDirectory(), "/nlog.config")); - Configuration = configuration; - } - - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - services.AddSingleton(); - services.AddMvc(); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerManager logger) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - - //app.ConfigureExceptionHandler(logger); - app.ConfigureCustomExceptionMiddleware(); - - app.UseMvc(); - } - } -} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.Development.json b/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.Development.json deleted file mode 100644 index fa8ce71..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.Development.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "Logging": { - "IncludeScopes": false, - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" - } - } -} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json b/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json deleted file mode 100644 index 26bb0ac..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "Logging": { - "IncludeScopes": false, - "Debug": { - "LogLevel": { - "Default": "Warning" - } - }, - "Console": { - "LogLevel": { - "Default": "Warning" - } - } - } -} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/nlog.config b/GlobalErrorHandling-End/GlobalErrorHandling/nlog.config deleted file mode 100644 index 9d888c8..0000000 --- a/GlobalErrorHandling-End/GlobalErrorHandling/nlog.config +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - diff --git a/GlobalErrorHandling-End/LoggerService/ILoggerManager.cs b/GlobalErrorHandling-End/LoggerService/ILoggerManager.cs deleted file mode 100644 index 5aa40c7..0000000 --- a/GlobalErrorHandling-End/LoggerService/ILoggerManager.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace LoggerService -{ - public interface ILoggerManager - { - void LogInfo(string message); - void LogWarn(string message); - void LogDebug(string message); - void LogError(string message); - } -} diff --git a/GlobalErrorHandling-End/LoggerService/LoggerManager.cs b/GlobalErrorHandling-End/LoggerService/LoggerManager.cs deleted file mode 100644 index 8c6502d..0000000 --- a/GlobalErrorHandling-End/LoggerService/LoggerManager.cs +++ /dev/null @@ -1,34 +0,0 @@ -using NLog; -using System; - -namespace LoggerService -{ - public class LoggerManager : ILoggerManager - { - private static ILogger logger = LogManager.GetCurrentClassLogger(); - - public LoggerManager() - { - } - - public void LogDebug(string message) - { - logger.Debug(message); - } - - public void LogError(string message) - { - logger.Error(message); - } - - public void LogInfo(string message) - { - logger.Info(message); - } - - public void LogWarn(string message) - { - logger.Warn(message); - } - } -} diff --git a/GlobalErrorHandling-End/LoggerService/LoggerService.csproj b/GlobalErrorHandling-End/LoggerService/LoggerService.csproj deleted file mode 100644 index 510f5b6..0000000 --- a/GlobalErrorHandling-End/LoggerService/LoggerService.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - netcoreapp2.0 - - - - - - - From e6b799ad178119ac1fa825a0143db9bad33fe7e4 Mon Sep 17 00:00:00 2001 From: Marinko Date: Mon, 18 Feb 2019 20:12:44 +0100 Subject: [PATCH 05/10] Added support for .NET Core 2.2 --- .gitignore | 5 ++ .../GlobalErrorHandling.sln | 31 ++++++++++ .../Controllers/ValuesController.cs | 36 ++++++++++++ .../ExceptionMiddleware.cs | 46 +++++++++++++++ .../GlobalErrorHandling/DataManager.cs | 19 +++++++ .../ExceptionMiddlewareExtensions.cs | 42 ++++++++++++++ .../GlobalErrorHandling.csproj | 17 ++++++ .../GlobalErrorHandling.csproj.user | 9 +++ .../Models/ErrorDetails.cs | 16 ++++++ .../GlobalErrorHandling/Models/Student.cs | 15 +++++ .../GlobalErrorHandling/Program.cs | 24 ++++++++ .../Properties/launchSettings.json | 30 ++++++++++ .../GlobalErrorHandling/Startup.cs | 57 +++++++++++++++++++ .../appsettings.Development.json | 9 +++ .../GlobalErrorHandling/appsettings.json | 8 +++ .../GlobalErrorHandling/nlog.config | 17 ++++++ .../LoggerService/ILoggerManager.cs | 14 +++++ .../LoggerService/LoggerManager.cs | 34 +++++++++++ .../LoggerService/LoggerService.csproj | 11 ++++ 19 files changed, 440 insertions(+) create mode 100644 .gitignore create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling.sln create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/DataManager.cs create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Program.cs create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/appsettings.Development.json create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json create mode 100644 GlobalErrorHandling-End/GlobalErrorHandling/nlog.config create mode 100644 GlobalErrorHandling-End/LoggerService/ILoggerManager.cs create mode 100644 GlobalErrorHandling-End/LoggerService/LoggerManager.cs create mode 100644 GlobalErrorHandling-End/LoggerService/LoggerService.csproj diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9491f31 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/GlobalErrorHandling-End/.vs +/GlobalErrorHandling-End/GlobalErrorHandling/obj +/GlobalErrorHandling-End/GlobalErrorHandling/bin +/GlobalErrorHandling-End/LoggerService/obj +/GlobalErrorHandling-End/LoggerService/bin diff --git a/GlobalErrorHandling-End/GlobalErrorHandling.sln b/GlobalErrorHandling-End/GlobalErrorHandling.sln new file mode 100644 index 0000000..6037e36 --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28307.421 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GlobalErrorHandling", "GlobalErrorHandling\GlobalErrorHandling.csproj", "{2A1E3F93-105E-4325-8939-E35B461C74CC}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LoggerService", "LoggerService\LoggerService.csproj", "{B941742F-8894-43F2-B61F-114D128116AB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2A1E3F93-105E-4325-8939-E35B461C74CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2A1E3F93-105E-4325-8939-E35B461C74CC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2A1E3F93-105E-4325-8939-E35B461C74CC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2A1E3F93-105E-4325-8939-E35B461C74CC}.Release|Any CPU.Build.0 = Release|Any CPU + {B941742F-8894-43F2-B61F-114D128116AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B941742F-8894-43F2-B61F-114D128116AB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B941742F-8894-43F2-B61F-114D128116AB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B941742F-8894-43F2-B61F-114D128116AB}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {49BDB31F-4741-4C4F-836F-6BF24E2DF609} + EndGlobalSection +EndGlobal diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs new file mode 100644 index 0000000..07904b9 --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using LoggerService; +using Microsoft.AspNetCore.Mvc; + +namespace GlobalErrorHandling.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class ValuesController : ControllerBase + { + private ILoggerManager _logger; + + public ValuesController(ILoggerManager logger) + { + _logger = logger; + } + + // GET api/values + [HttpGet] + public ActionResult> Get() + { + _logger.LogInfo("Fetching all the Students from the storage"); + + var students = DataManager.GetAllStudents(); //simulation for the data base access + + throw new Exception("Exception while fetching all the students from the storage."); + + _logger.LogInfo($"Returning {students.Count} students."); + + return Ok(students); + } + } +} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs b/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs new file mode 100644 index 0000000..f579520 --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs @@ -0,0 +1,46 @@ +using GlobalErrorHandling.Models; +using LoggerService; +using Microsoft.AspNetCore.Http; +using System; +using System.Net; +using System.Threading.Tasks; + +namespace GlobalErrorHandling.CustomExceptionMiddleware +{ + public class ExceptionMiddleware + { + private readonly RequestDelegate _next; + private readonly ILoggerManager _logger; + + public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger) + { + _logger = logger; + _next = next; + } + + public async Task InvokeAsync(HttpContext httpContext) + { + try + { + await _next(httpContext); + } + catch (Exception ex) + { + _logger.LogError($"Something went wrong: {ex}"); + await HandleExceptionAsync(httpContext, ex); + } + } + + private static Task HandleExceptionAsync(HttpContext context, Exception exception) + { + context.Response.ContentType = "application/json"; + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + + return context.Response.WriteAsync(new ErrorDetails() + { + StatusCode = context.Response.StatusCode, + Message = "Internal Server Error from the custom middleware." + }.ToString()); + } + } +} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/DataManager.cs b/GlobalErrorHandling-End/GlobalErrorHandling/DataManager.cs new file mode 100644 index 0000000..6e1d96e --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/DataManager.cs @@ -0,0 +1,19 @@ +using GlobalErrorHandling.Models; +using System.Collections.Generic; + +namespace GlobalErrorHandling +{ + public class DataManager + { + public static List GetAllStudents() + { + return new List + { + new Student { Name="Joe", LastName="Doe", Age=35, Gender="Male"}, + new Student { Name="Jane", LastName="Doe", Age=25, Gender="Female"}, + new Student { Name="Mick", LastName="Simon", Age=32, Gender="Male"}, + new Student { Name="Sandra", LastName="Summer", Age=30, Gender="Female"}, + }; + } + } +} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs new file mode 100644 index 0000000..0480604 --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs @@ -0,0 +1,42 @@ +using GlobalErrorHandling.CustomExceptionMiddleware; +using GlobalErrorHandling.Models; +using LoggerService; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics; +using Microsoft.AspNetCore.Http; +using System.Net; + +namespace GlobalErrorHandling.Extensions +{ + public static class ExceptionMiddlewareExtensions + { + public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILoggerManager logger) + { + app.UseExceptionHandler(appError => + { + appError.Run(async context => + { + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + context.Response.ContentType = "application/json"; + + var contextFeature = context.Features.Get(); + if(contextFeature != null) + { + logger.LogError($"Something went wrong: {contextFeature.Error}"); + + await context.Response.WriteAsync(new ErrorDetails() + { + StatusCode = context.Response.StatusCode, + Message = "Internal Server Error." + }.ToString()); + } + }); + }); + } + + public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app) + { + app.UseMiddleware(); + } + } +} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj new file mode 100644 index 0000000..e43d77d --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj @@ -0,0 +1,17 @@ + + + + netcoreapp2.2 + InProcess + + + + + + + + + + + + diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user new file mode 100644 index 0000000..0776e7f --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user @@ -0,0 +1,9 @@ + + + + ProjectDebugger + + + GlobalErrorHandling + + \ No newline at end of file diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs new file mode 100644 index 0000000..9830a5c --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs @@ -0,0 +1,16 @@ +using Newtonsoft.Json; + +namespace GlobalErrorHandling.Models +{ + public class ErrorDetails + { + public int StatusCode { get; set; } + public string Message { get; set; } + + + public override string ToString() + { + return JsonConvert.SerializeObject(this); + } + } +} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs new file mode 100644 index 0000000..5be9144 --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace GlobalErrorHandling.Models +{ + public class Student + { + public string Name { get; set; } + public string LastName { get; set; } + public int Age { get; set; } + public string Gender { get; set; } + } +} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Program.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Program.cs new file mode 100644 index 0000000..1324f08 --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Program.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; + +namespace GlobalErrorHandling +{ + public class Program + { + public static void Main(string[] args) + { + CreateWebHostBuilder(args).Build().Run(); + } + + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup(); + } +} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json b/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json new file mode 100644 index 0000000..9a8d3cb --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json @@ -0,0 +1,30 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:62163", + "sslPort": 44388 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "api/values", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "GlobalErrorHandling": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "api/values", + "applicationUrl": "http://localhost:55761", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs new file mode 100644 index 0000000..7243192 --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using GlobalErrorHandling.Extensions; +using LoggerService; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.HttpsPolicy; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NLog; + +namespace GlobalErrorHandling +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + LogManager.LoadConfiguration(String.Concat(Directory.GetCurrentDirectory(), "/nlog.config")); + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddSingleton(); + services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerManager logger) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + else + { + // 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.ConfigureExceptionHandler(logger); + app.ConfigureCustomExceptionMiddleware(); + + app.UseHttpsRedirection(); + app.UseMvc(); + } + } +} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.Development.json b/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.Development.json new file mode 100644 index 0000000..e203e94 --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + } +} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json b/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json new file mode 100644 index 0000000..def9159 --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/nlog.config b/GlobalErrorHandling-End/GlobalErrorHandling/nlog.config new file mode 100644 index 0000000..a6fd586 --- /dev/null +++ b/GlobalErrorHandling-End/GlobalErrorHandling/nlog.config @@ -0,0 +1,17 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/GlobalErrorHandling-End/LoggerService/ILoggerManager.cs b/GlobalErrorHandling-End/LoggerService/ILoggerManager.cs new file mode 100644 index 0000000..5aa40c7 --- /dev/null +++ b/GlobalErrorHandling-End/LoggerService/ILoggerManager.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace LoggerService +{ + public interface ILoggerManager + { + void LogInfo(string message); + void LogWarn(string message); + void LogDebug(string message); + void LogError(string message); + } +} diff --git a/GlobalErrorHandling-End/LoggerService/LoggerManager.cs b/GlobalErrorHandling-End/LoggerService/LoggerManager.cs new file mode 100644 index 0000000..8c6502d --- /dev/null +++ b/GlobalErrorHandling-End/LoggerService/LoggerManager.cs @@ -0,0 +1,34 @@ +using NLog; +using System; + +namespace LoggerService +{ + public class LoggerManager : ILoggerManager + { + private static ILogger logger = LogManager.GetCurrentClassLogger(); + + public LoggerManager() + { + } + + public void LogDebug(string message) + { + logger.Debug(message); + } + + public void LogError(string message) + { + logger.Error(message); + } + + public void LogInfo(string message) + { + logger.Info(message); + } + + public void LogWarn(string message) + { + logger.Warn(message); + } + } +} diff --git a/GlobalErrorHandling-End/LoggerService/LoggerService.csproj b/GlobalErrorHandling-End/LoggerService/LoggerService.csproj new file mode 100644 index 0000000..510f5b6 --- /dev/null +++ b/GlobalErrorHandling-End/LoggerService/LoggerService.csproj @@ -0,0 +1,11 @@ + + + + netcoreapp2.0 + + + + + + + From fd74648edfe25852b13f512669e1c49134cae1a4 Mon Sep 17 00:00:00 2001 From: Marinko Date: Sun, 4 Aug 2019 18:45:09 +0200 Subject: [PATCH 06/10] Removed static keyword from method signature. --- .../CustomExceptionMiddleware/ExceptionMiddleware.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs b/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs index f579520..6d09e03 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs +++ b/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs @@ -31,7 +31,7 @@ public async Task InvokeAsync(HttpContext httpContext) } } - private static Task HandleExceptionAsync(HttpContext context, Exception exception) + private Task HandleExceptionAsync(HttpContext context, Exception exception) { context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; From 3471c10b1dad5e180c9dc00e2a088ef9ae704f29 Mon Sep 17 00:00:00 2001 From: Marinko Date: Wed, 23 Oct 2019 18:05:05 +0200 Subject: [PATCH 07/10] Support for ASP.NET Core 3.0 --- .../GlobalErrorHandling.sln | 26 ++++++++-------- .../Controllers/ValuesController.cs | 10 ++---- .../ExceptionMiddlewareExtensions.cs | 4 +-- .../GlobalErrorHandling.csproj | 12 ++++--- .../GlobalErrorHandling.csproj.user | 10 +++++- .../Models/ErrorDetails.cs | 7 ++--- .../GlobalErrorHandling/Models/Student.cs | 7 +---- .../GlobalErrorHandling/Program.cs | 20 +++++------- .../Properties/launchSettings.json | 6 ++-- .../GlobalErrorHandling/Startup.cs | 31 +++++++++---------- .../GlobalErrorHandling/appsettings.json | 4 ++- .../LoggerService/ILoggerManager.cs | 6 +--- .../LoggerService/LoggerManager.cs | 1 - .../LoggerService/LoggerService.csproj | 4 +-- 14 files changed, 70 insertions(+), 78 deletions(-) diff --git a/GlobalErrorHandling-End/GlobalErrorHandling.sln b/GlobalErrorHandling-End/GlobalErrorHandling.sln index 6037e36..6f2aa32 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling.sln +++ b/GlobalErrorHandling-End/GlobalErrorHandling.sln @@ -1,11 +1,11 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.28307.421 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29418.71 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GlobalErrorHandling", "GlobalErrorHandling\GlobalErrorHandling.csproj", "{2A1E3F93-105E-4325-8939-E35B461C74CC}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GlobalErrorHandling", "GlobalErrorHandling\GlobalErrorHandling.csproj", "{AF62693C-1877-485B-865D-C3CAEB2CBA12}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LoggerService", "LoggerService\LoggerService.csproj", "{B941742F-8894-43F2-B61F-114D128116AB}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LoggerService", "LoggerService\LoggerService.csproj", "{B61D597A-BF38-4F7D-BE39-C024B59C114D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -13,19 +13,19 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2A1E3F93-105E-4325-8939-E35B461C74CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2A1E3F93-105E-4325-8939-E35B461C74CC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2A1E3F93-105E-4325-8939-E35B461C74CC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2A1E3F93-105E-4325-8939-E35B461C74CC}.Release|Any CPU.Build.0 = Release|Any CPU - {B941742F-8894-43F2-B61F-114D128116AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B941742F-8894-43F2-B61F-114D128116AB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B941742F-8894-43F2-B61F-114D128116AB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B941742F-8894-43F2-B61F-114D128116AB}.Release|Any CPU.Build.0 = Release|Any CPU + {AF62693C-1877-485B-865D-C3CAEB2CBA12}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AF62693C-1877-485B-865D-C3CAEB2CBA12}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AF62693C-1877-485B-865D-C3CAEB2CBA12}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AF62693C-1877-485B-865D-C3CAEB2CBA12}.Release|Any CPU.Build.0 = Release|Any CPU + {B61D597A-BF38-4F7D-BE39-C024B59C114D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B61D597A-BF38-4F7D-BE39-C024B59C114D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B61D597A-BF38-4F7D-BE39-C024B59C114D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B61D597A-BF38-4F7D-BE39-C024B59C114D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {49BDB31F-4741-4C4F-836F-6BF24E2DF609} + SolutionGuid = {EF9B2F79-1783-4500-B905-45712FB7606D} EndGlobalSection EndGlobal diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs index 07904b9..98ef20f 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using LoggerService; using Microsoft.AspNetCore.Mvc; @@ -12,16 +9,15 @@ namespace GlobalErrorHandling.Controllers public class ValuesController : ControllerBase { private ILoggerManager _logger; - public ValuesController(ILoggerManager logger) { _logger = logger; } - // GET api/values [HttpGet] - public ActionResult> Get() + public IActionResult Get() { + _logger.LogInfo("Fetching all the Students from the storage"); var students = DataManager.GetAllStudents(); //simulation for the data base access @@ -33,4 +29,4 @@ public ActionResult> Get() return Ok(students); } } -} +} \ No newline at end of file diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs index 0480604..c45edb3 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Extensions/ExceptionMiddlewareExtensions.cs @@ -20,8 +20,8 @@ public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILogg context.Response.ContentType = "application/json"; var contextFeature = context.Features.Get(); - if(contextFeature != null) - { + if (contextFeature != null) + { logger.LogError($"Something went wrong: {contextFeature.Error}"); await context.Response.WriteAsync(new ErrorDetails() diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj index e43d77d..82a03da 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj +++ b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj @@ -1,13 +1,17 @@ - netcoreapp2.2 - InProcess + netcoreapp3.0 - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user index 0776e7f..2a7762e 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user +++ b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj.user @@ -1,9 +1,17 @@  - + ProjectDebugger GlobalErrorHandling + ApiControllerEmptyScaffolder + root/Controller + 600 + True + False + True + + False \ No newline at end of file diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs index 9830a5c..0a2336b 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs @@ -7,10 +7,9 @@ public class ErrorDetails public int StatusCode { get; set; } public string Message { get; set; } - - public override string ToString() - { - return JsonConvert.SerializeObject(this); + public override string ToString() + { + return JsonConvert.SerializeObject(this); } } } diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs index 5be9144..ea142e1 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Models/Student.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace GlobalErrorHandling.Models +namespace GlobalErrorHandling.Models { public class Student { diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Program.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Program.cs index 1324f08..9cbb5a4 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Program.cs +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Program.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Hosting; namespace GlobalErrorHandling { @@ -14,11 +7,14 @@ public class Program { public static void Main(string[] args) { - CreateWebHostBuilder(args).Build().Run(); + CreateHostBuilder(args).Build().Run(); } - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup(); + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); } } diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json b/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json index 9a8d3cb..b831277 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json @@ -1,8 +1,8 @@ { "$schema": "http://json.schemastore.org/launchsettings.json", "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, + "windowsAuthentication": false, + "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:62163", "sslPort": 44388 @@ -19,7 +19,7 @@ }, "GlobalErrorHandling": { "commandName": "Project", - "launchBrowser": true, + "launchBrowser": false, "launchUrl": "api/values", "applicationUrl": "http://localhost:55761", "environmentVariables": { diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs index 7243192..10bafd8 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Startup.cs @@ -1,18 +1,11 @@ -using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Threading.Tasks; using GlobalErrorHandling.Extensions; using LoggerService; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.HttpsPolicy; -using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; +using Microsoft.Extensions.Hosting; using NLog; namespace GlobalErrorHandling @@ -21,7 +14,7 @@ public class Startup { public Startup(IConfiguration configuration) { - LogManager.LoadConfiguration(String.Concat(Directory.GetCurrentDirectory(), "/nlog.config")); + LogManager.LoadConfiguration(string.Concat(Directory.GetCurrentDirectory(), "/nlog.config")); Configuration = configuration; } @@ -31,27 +24,31 @@ public Startup(IConfiguration configuration) public void ConfigureServices(IServiceCollection services) { services.AddSingleton(); - services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + + services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerManager logger) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerManager logger) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } - else - { - // 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.ConfigureExceptionHandler(logger); app.ConfigureCustomExceptionMiddleware(); app.UseHttpsRedirection(); - app.UseMvc(); + + app.UseRouting(); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); } } } diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json b/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json index def9159..d9d9a9b 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json +++ b/GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json @@ -1,7 +1,9 @@ { "Logging": { "LogLevel": { - "Default": "Warning" + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" diff --git a/GlobalErrorHandling-End/LoggerService/ILoggerManager.cs b/GlobalErrorHandling-End/LoggerService/ILoggerManager.cs index 5aa40c7..433d91e 100644 --- a/GlobalErrorHandling-End/LoggerService/ILoggerManager.cs +++ b/GlobalErrorHandling-End/LoggerService/ILoggerManager.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace LoggerService +namespace LoggerService { public interface ILoggerManager { diff --git a/GlobalErrorHandling-End/LoggerService/LoggerManager.cs b/GlobalErrorHandling-End/LoggerService/LoggerManager.cs index 8c6502d..f888b11 100644 --- a/GlobalErrorHandling-End/LoggerService/LoggerManager.cs +++ b/GlobalErrorHandling-End/LoggerService/LoggerManager.cs @@ -1,5 +1,4 @@ using NLog; -using System; namespace LoggerService { diff --git a/GlobalErrorHandling-End/LoggerService/LoggerService.csproj b/GlobalErrorHandling-End/LoggerService/LoggerService.csproj index 510f5b6..9a3d507 100644 --- a/GlobalErrorHandling-End/LoggerService/LoggerService.csproj +++ b/GlobalErrorHandling-End/LoggerService/LoggerService.csproj @@ -1,11 +1,11 @@ - netcoreapp2.0 + netcoreapp3.0 - + From d75def5c5141767c14ec48998626b4a0ca3114c5 Mon Sep 17 00:00:00 2001 From: Marinko Date: Fri, 3 Jan 2020 13:27:14 +0100 Subject: [PATCH 08/10] 3.1 support --- .../GlobalErrorHandling/GlobalErrorHandling.csproj | 10 +++++----- .../LoggerService/LoggerService.csproj | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj index 82a03da..78aa38a 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj +++ b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj @@ -1,17 +1,17 @@ - netcoreapp3.0 + netcoreapp3.1 - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + diff --git a/GlobalErrorHandling-End/LoggerService/LoggerService.csproj b/GlobalErrorHandling-End/LoggerService/LoggerService.csproj index 9a3d507..ba98778 100644 --- a/GlobalErrorHandling-End/LoggerService/LoggerService.csproj +++ b/GlobalErrorHandling-End/LoggerService/LoggerService.csproj @@ -1,7 +1,7 @@ - netcoreapp3.0 + netcoreapp3.1 From db059c48f508a1ca08f22bb6ce9682ba430bafb4 Mon Sep 17 00:00:00 2001 From: Marinko Date: Thu, 10 Jun 2021 10:50:57 +0200 Subject: [PATCH 09/10] Update to .NET 5 --- .../GlobalErrorHandling.csproj | 10 +++++----- .../GlobalErrorHandling/Models/ErrorDetails.cs | 4 ++-- .../Properties/launchSettings.json | 17 ----------------- .../LoggerService/LoggerService.csproj | 4 ++-- 4 files changed, 9 insertions(+), 26 deletions(-) diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj index 78aa38a..a26d17e 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj +++ b/GlobalErrorHandling-End/GlobalErrorHandling/GlobalErrorHandling.csproj @@ -1,17 +1,17 @@ - netcoreapp3.1 + net5.0 - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs index 0a2336b..3283340 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs @@ -1,4 +1,4 @@ -using Newtonsoft.Json; +using System.Text.Json; namespace GlobalErrorHandling.Models { @@ -9,7 +9,7 @@ public class ErrorDetails public override string ToString() { - return JsonConvert.SerializeObject(this); + return JsonSerializer.Serialize(this); } } } diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json b/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json index b831277..7349f3b 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Properties/launchSettings.json @@ -1,22 +1,5 @@ { - "$schema": "http://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:62163", - "sslPort": 44388 - } - }, "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "api/values", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, "GlobalErrorHandling": { "commandName": "Project", "launchBrowser": false, diff --git a/GlobalErrorHandling-End/LoggerService/LoggerService.csproj b/GlobalErrorHandling-End/LoggerService/LoggerService.csproj index ba98778..32851dc 100644 --- a/GlobalErrorHandling-End/LoggerService/LoggerService.csproj +++ b/GlobalErrorHandling-End/LoggerService/LoggerService.csproj @@ -1,11 +1,11 @@ - netcoreapp3.1 + net5.0 - + From 2aaf4642bb62a9fecb2bacaad1658d2d968990dc Mon Sep 17 00:00:00 2001 From: Marinko Date: Thu, 10 Jun 2021 12:32:42 +0200 Subject: [PATCH 10/10] Custom error messages. --- .../Controllers/ValuesController.cs | 39 +++++----- .../ExceptionMiddleware.cs | 75 +++++++++++-------- 2 files changed, 62 insertions(+), 52 deletions(-) diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs b/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs index 98ef20f..e2e3257 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs +++ b/GlobalErrorHandling-End/GlobalErrorHandling/Controllers/ValuesController.cs @@ -4,29 +4,28 @@ namespace GlobalErrorHandling.Controllers { - [Route("api/[controller]")] - [ApiController] - public class ValuesController : ControllerBase - { - private ILoggerManager _logger; - public ValuesController(ILoggerManager logger) - { - _logger = logger; - } + [Route("api/[controller]")] + [ApiController] + public class ValuesController : ControllerBase + { + private ILoggerManager _logger; + public ValuesController(ILoggerManager logger) + { + _logger = logger; + } - [HttpGet] - public IActionResult Get() - { + [HttpGet] + public IActionResult Get() + { + _logger.LogInfo("Fetching all the Students from the storage"); - _logger.LogInfo("Fetching all the Students from the storage"); + var students = DataManager.GetAllStudents(); //simulation for the data base access - var students = DataManager.GetAllStudents(); //simulation for the data base access + throw new AccessViolationException("Violation Exception while accessing the resource."); - throw new Exception("Exception while fetching all the students from the storage."); + _logger.LogInfo($"Returning {students.Count} students."); - _logger.LogInfo($"Returning {students.Count} students."); - - return Ok(students); - } - } + return Ok(students); + } + } } \ No newline at end of file diff --git a/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs b/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs index 6d09e03..ad54e01 100644 --- a/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs +++ b/GlobalErrorHandling-End/GlobalErrorHandling/CustomExceptionMiddleware/ExceptionMiddleware.cs @@ -7,40 +7,51 @@ namespace GlobalErrorHandling.CustomExceptionMiddleware { - public class ExceptionMiddleware - { - private readonly RequestDelegate _next; - private readonly ILoggerManager _logger; + public class ExceptionMiddleware + { + private readonly RequestDelegate _next; + private readonly ILoggerManager _logger; - public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger) - { - _logger = logger; - _next = next; - } + public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger) + { + _logger = logger; + _next = next; + } - public async Task InvokeAsync(HttpContext httpContext) - { - try - { - await _next(httpContext); - } - catch (Exception ex) - { - _logger.LogError($"Something went wrong: {ex}"); - await HandleExceptionAsync(httpContext, ex); - } - } + public async Task InvokeAsync(HttpContext httpContext) + { + try + { + await _next(httpContext); + } + catch (AccessViolationException avEx) + { + _logger.LogError($"A new violation exception has been thrown: {avEx}"); + await HandleExceptionAsync(httpContext, avEx); + } + catch (Exception ex) + { + _logger.LogError($"Something went wrong: {ex}"); + await HandleExceptionAsync(httpContext, ex); + } + } - private Task HandleExceptionAsync(HttpContext context, Exception exception) - { - context.Response.ContentType = "application/json"; - context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + private async Task HandleExceptionAsync(HttpContext context, Exception exception) + { + context.Response.ContentType = "application/json"; + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; - return context.Response.WriteAsync(new ErrorDetails() - { - StatusCode = context.Response.StatusCode, - Message = "Internal Server Error from the custom middleware." - }.ToString()); - } - } + var message = exception switch + { + AccessViolationException => "Access violation error from the custom middleware", + _ => "Internal Server Error from the custom middleware." + }; + + await context.Response.WriteAsync(new ErrorDetails() + { + StatusCode = context.Response.StatusCode, + Message = message + }.ToString()); + } + } }