-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathErrorHandlerMiddleware.cs
71 lines (65 loc) · 2.25 KB
/
ErrorHandlerMiddleware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
namespace Collections.API.MIddleware
{
/// <summary>
/// Middleware for handling errors and exceptions in the API
/// </summary>
public class ErrorHandlerMiddleware
{
/// <summary>
/// The next request
/// </summary>
private readonly RequestDelegate next;
/// <summary>
/// Initializes a new instance of the <see cref="ErrorHandlerMiddleware"/> class.
/// </summary>
/// <param name="next">The next request.</param>
public ErrorHandlerMiddleware(RequestDelegate next)
{
this.next = next;
}
/// <summary>
/// Invokes the middleware for the context.
/// </summary>
/// <param name="context">The current context.</param>
/// <returns>An instenace of <see cref="Task"/>.</returns>
public async Task Invoke(HttpContext context)
{
try
{
await this.next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
/// <summary>
/// Handles exceptions thrown when processing requests.
/// </summary>
/// <param name="context">The current context.</param>
/// <param name="exception">The exception thrown when processing the request.</param>
/// <returns>An instance of <see cref="Task"/>.</returns>
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var code = HttpStatusCode.InternalServerError;
if (exception is KeyNotFoundException)
{
code = HttpStatusCode.NotFound;
}
else if (exception is ArgumentNullException)
{
code = HttpStatusCode.BadRequest;
}
var result = JsonConvert.SerializeObject(new { error = exception.Message });
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);
}
}
}