Skip to content

Commit 3504040

Browse files
author
Marcin Liszewski
committed
added middleware with error handling example
1 parent 77815d5 commit 3504040

File tree

4 files changed

+114
-2
lines changed

4 files changed

+114
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 319 Samples for ASP.NET Core 3.1.300 and ASP.NET Core 5 RC1
1+
# 320 Samples for ASP.NET Core 3.1.300 and ASP.NET Core 5 RC1
22

33
## People of Beirut needs our help. [Please support them](https://lebanoncrisis.carrd.co/#donate).
44

@@ -21,7 +21,7 @@ Hi Nuget visitors, if you have problem finding the sample you are looking for, p
2121

2222
| Section | | | |
2323
|-----------------------------------------------------------------|------|-----------------------------------------------------------------------------------------------------------------|------|
24-
| [Blazor Client Side (Web Assembly)](/projects/blazor/README.md) (Components, Data Binding) | (20) | [Middleware](/projects/middleware) | (13) |
24+
| [Blazor Client Side (Web Assembly)](/projects/blazor/README.md) (Components, Data Binding) | (20) | [Middleware](/projects/middleware) | (14) |
2525
| [Blazor Server Side](/projects/blazor-ss) (Localization) | (15) | [MVC](/projects/mvc) (Localization, Routing, Razor Class Library, Tag Helpers, View Component, etc) | (46) |
2626
| [Caching](/projects/caching) | (5) | [Razor Pages](/projects/razor-pages) | (9) |
2727
| [Configurations](/projects/configurations) | (7) | [Orchard Core](/projects/orchard-core) | (4) |

projects/middleware/README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,7 @@
5959
* [Middleware 12](/projects/middleware/middleware-12)
6060

6161
Contrast the usage of `MapWhen` (which branch execution) and `UseWhen` (which doesn't branch execution) in configuring your Middleware.
62+
63+
* [Middleware 13](/projects/middleware/middleware-13)
64+
65+
Demonstrate how to implement basic error handling mechanism and how to return error object (same for all api exceptions).
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>netcoreapp3.1</TargetFramework>
5+
<RootNamespace>middleware_13</RootNamespace>
6+
</PropertyGroup>
7+
8+
9+
</Project>
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
using System;
2+
using System.Net;
3+
using System.Text.Json;
4+
using System.Threading.Tasks;
5+
using Microsoft.AspNetCore.Builder;
6+
using Microsoft.AspNetCore.Hosting;
7+
using Microsoft.AspNetCore.Http;
8+
using Microsoft.Extensions.Hosting;
9+
using Microsoft.Extensions.Logging;
10+
11+
namespace middleware_13
12+
{
13+
public class Program
14+
{
15+
public static void Main(string[] args)
16+
{
17+
CreateHostBuilder(args).Build().Run();
18+
}
19+
20+
public static IHostBuilder CreateHostBuilder(string[] args) =>
21+
Host.CreateDefaultBuilder(args)
22+
.ConfigureWebHostDefaults(webBuilder =>
23+
{
24+
webBuilder.UseStartup<Startup>();
25+
});
26+
}
27+
28+
public class Startup
29+
{
30+
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
31+
{
32+
app.UseMiddleware<ErrorHandlingMiddleware>();
33+
}
34+
}
35+
36+
public interface ICustomApiException
37+
{
38+
HttpStatusCode HttpStatus { get; }
39+
string HttpMessage { get; }
40+
}
41+
42+
public class ExampleApiException : Exception, ICustomApiException
43+
{
44+
public HttpStatusCode HttpStatus => HttpStatusCode.Forbidden;
45+
public string HttpMessage => "Resource cannot be accessed.";
46+
47+
public ExampleApiException(string message) : base(message)
48+
{
49+
}
50+
}
51+
52+
public class ErrorDto
53+
{
54+
public int Status { get; set; }
55+
public string Message { get; set; }
56+
}
57+
58+
public class ErrorHandlingMiddleware : IMiddleware
59+
{
60+
private readonly ILogger<ErrorHandlingMiddleware> _logger;
61+
62+
public ErrorHandlingMiddleware(ILogger<ErrorHandlingMiddleware> logger)
63+
{
64+
_logger = logger;
65+
}
66+
67+
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
68+
{
69+
try
70+
{
71+
await next.Invoke(context);
72+
}
73+
catch (Exception ex)
74+
{
75+
_logger.LogError(ex, ex.Message);
76+
77+
var httpStatus = HttpStatusCode.InternalServerError;
78+
var httpMessage = "Internal Server Error";
79+
80+
if (ex is ICustomApiException customException)
81+
{
82+
httpStatus = customException.HttpStatus;
83+
httpMessage = customException.HttpMessage;
84+
}
85+
86+
context.Response.StatusCode = (int)httpStatus;
87+
context.Response.ContentType = "application/json";
88+
89+
var error = new ErrorDto()
90+
{
91+
Status = (int)httpStatus,
92+
Message = httpMessage
93+
};
94+
95+
await context.Response.WriteAsync(JsonSerializer.Serialize(error));
96+
}
97+
}
98+
}
99+
}

0 commit comments

Comments
 (0)