-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExceptionHandlerMiddleware.cs
67 lines (60 loc) · 2.36 KB
/
ExceptionHandlerMiddleware.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
//-----------------------------------------------------------------------
// <copyright file="ExceptionHandlerMiddleware.cs" company="Microsoft Corp.">
// Copyright (c) Microsoft Corp. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.ArmSwashbuckleStarterKit.Middlewares
{
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.ArmSwashbuckleStarterKit.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
public class ExceptionHandlerMiddleware
{
private static readonly string InternalErrorMessage = "Please contact Microsoft EdgeRP development team at edgerp@microsoft.com";
private readonly RequestDelegate next;
private readonly ILogger<ExceptionHandlerMiddleware> logger;
public ExceptionHandlerMiddleware(
RequestDelegate next,
ILogger<ExceptionHandlerMiddleware> logger)
{
this.next = next;
this.logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await this.next(context);
}
catch (Exception e)
{
var armErrorDetail = new ArmErrorDetail
{
Code = "500", // TODO: derive status code from exception
Message = InternalErrorMessage,
Details = new ArmErrorDetail[]
{
new ArmErrorDetail
{
Code = "500",
Message = e.Message,
Target = e.TargetSite.ToString()
}
}
};
var errorResponse = new ArmErrorResponse { Error = armErrorDetail };
this.SendErrorResponse(context, errorResponse, 500);
}
}
private async void SendErrorResponse(HttpContext context, ArmErrorResponse errorResponse, int statusCode)
{
context.Response.StatusCode = statusCode;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse));
}
}
}