-
Notifications
You must be signed in to change notification settings - Fork 146
/
JsonExceptionMiddleware.cs
64 lines (53 loc) · 1.85 KB
/
JsonExceptionMiddleware.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
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using BeautifulRestApi.Models;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace BeautifulRestApi.Infrastructure
{
public sealed class JsonExceptionMiddleware
{
public const string DefaultErrorMessage = "A server error occurred.";
private readonly IHostingEnvironment _env;
private readonly JsonSerializer _serializer;
public JsonExceptionMiddleware(IHostingEnvironment env)
{
_env = env;
_serializer = new JsonSerializer();
_serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
public async Task Invoke(HttpContext context)
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
var ex = context.Features.Get<IExceptionHandlerFeature>()?.Error;
if (ex == null) return;
var error = BuildError(ex, _env);
using (var writer = new StreamWriter(context.Response.Body))
{
_serializer.Serialize(writer, error);
await writer.FlushAsync().ConfigureAwait(false);
}
}
private static ApiError BuildError(Exception ex, IHostingEnvironment env)
{
var error = new ApiError();
if (env.IsDevelopment())
{
error.Message = ex.Message;
error.Detail = ex.StackTrace;
}
else
{
error.Message = DefaultErrorMessage;
error.Detail = ex.Message;
}
return error;
}
}
}