Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Global error handling end #4

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/GlobalErrorHandling-End/.vs
/GlobalErrorHandling-End/GlobalErrorHandling/obj
/GlobalErrorHandling-End/GlobalErrorHandling/bin
/GlobalErrorHandling-End/LoggerService/obj
/GlobalErrorHandling-End/LoggerService/bin
31 changes: 31 additions & 0 deletions GlobalErrorHandling-End/GlobalErrorHandling.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29418.71
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GlobalErrorHandling", "GlobalErrorHandling\GlobalErrorHandling.csproj", "{AF62693C-1877-485B-865D-C3CAEB2CBA12}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LoggerService", "LoggerService\LoggerService.csproj", "{B61D597A-BF38-4F7D-BE39-C024B59C114D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{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 = {EF9B2F79-1783-4500-B905-45712FB7606D}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
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;
}

[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 AccessViolationException("Violation Exception while accessing the resource.");

_logger.LogInfo($"Returning {students.Count} students.");

return Ok(students);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
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 (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 async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

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());
}
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
using System;
using GlobalErrorHandling.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GlobalErrorHandling.Models;

namespace GlobalErrorHandling
{
public static class DataManager
public class DataManager
{
public static List<Student> GetAllStudents()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -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<IExceptionHandlerFeature>();
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<ExceptionMiddleware>();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.7">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="5.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\LoggerService\LoggerService.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup>
<ActiveDebugProfile>GlobalErrorHandling</ActiveDebugProfile>
<Controller_SelectedScaffolderID>ApiControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Controller</Controller_SelectedScaffolderCategoryPath>
<WebStackScaffolding_ControllerDialogWidth>600</WebStackScaffolding_ControllerDialogWidth>
<WebStackScaffolding_IsLayoutPageSelected>True</WebStackScaffolding_IsLayoutPageSelected>
<WebStackScaffolding_IsPartialViewSelected>False</WebStackScaffolding_IsPartialViewSelected>
<WebStackScaffolding_IsReferencingScriptLibrariesSelected>True</WebStackScaffolding_IsReferencingScriptLibrariesSelected>
<WebStackScaffolding_LayoutPageFile />
<WebStackScaffolding_IsAsyncSelected>False</WebStackScaffolding_IsAsyncSelected>
</PropertyGroup>
</Project>
15 changes: 15 additions & 0 deletions GlobalErrorHandling-End/GlobalErrorHandling/Models/ErrorDetails.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.Text.Json;

namespace GlobalErrorHandling.Models
{
public class ErrorDetails
{
public int StatusCode { get; set; }
public string Message { get; set; }

public override string ToString()
{
return JsonSerializer.Serialize(this);
}
}
}
Original file line number Diff line number Diff line change
@@ -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
{
Expand Down
20 changes: 20 additions & 0 deletions GlobalErrorHandling-End/GlobalErrorHandling/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace GlobalErrorHandling
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"profiles": {
"GlobalErrorHandling": {
"commandName": "Project",
"launchBrowser": false,
"launchUrl": "api/values",
"applicationUrl": "http://localhost:55761",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using System;
using System.IO;
using GlobalErrorHandling.Extensions;
using LoggerService;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NLog;

namespace GlobalErrorHandling
Expand All @@ -13,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;
}

Expand All @@ -23,18 +24,31 @@ public Startup(IConfiguration configuration)
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ILoggerManager, LoggerManager>();
services.AddMvc();

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)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerManager logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseMvc();
//app.ConfigureExceptionHandler(logger);
app.ConfigureCustomExceptionMiddleware();

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
Expand Down
10 changes: 10 additions & 0 deletions GlobalErrorHandling-End/GlobalErrorHandling/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@
internalLogLevel="Trace"
internalLogFile="c:/GlobalErrorHandlingLogs/internal_logs/internallog.txt">

<extensions>
<add assembly="NLog.Extended" />
</extensions>

<targets>
<target name="logfile" xsi:type="File"
fileName="c:/GlobalErrorHandlingLogs/logs/${shortdate}_logfile.txt"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace LoggerService
namespace LoggerService
{
public interface ILoggerManager
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using NLog;
using System;

namespace LoggerService
{
Expand Down
Loading