Skip to content

Commit 77e38c2

Browse files
committed
Custom error handle
Global Error Handling added
1 parent 8764d42 commit 77e38c2

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
using Microsoft.AspNetCore.Http;
2+
using Microsoft.Extensions.Logging;
3+
using Newtonsoft.Json;
4+
using Newtonsoft.Json.Serialization;
5+
using Supermarket.ApiResponse;
6+
using System;
7+
using System.Collections.Generic;
8+
using System.Linq;
9+
using System.Net;
10+
using System.Threading.Tasks;
11+
12+
namespace Supermarket.Middleware
13+
{
14+
public class ExceptionMiddleware
15+
{
16+
private readonly RequestDelegate _next;
17+
private readonly ILogger<ExceptionMiddleware> _logger;
18+
19+
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
20+
{
21+
_logger = logger;
22+
_next = next;
23+
}
24+
25+
public async Task InvokeAsync(HttpContext httpContext)
26+
{
27+
try
28+
{
29+
await _next(httpContext);
30+
}
31+
catch (Exception ex)
32+
{
33+
_logger.LogError($"API Error: {ex}");
34+
await HandleExceptionAsync(httpContext, ex);
35+
}
36+
}
37+
38+
private Task HandleExceptionAsync(HttpContext context, Exception exception)
39+
{
40+
var code = HttpStatusCode.InternalServerError; // 500 if unexpected
41+
42+
////Refer https://stackoverflow.com/questions/38630076/asp-net-core-web-api-exception-handling
43+
44+
var result = JsonConvert.SerializeObject(
45+
new InternalServerErrorResponse(exception.Message),
46+
Formatting.Indented,
47+
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
48+
);
49+
_logger.LogError(result);
50+
context.Response.ContentType = "application/json";
51+
context.Response.StatusCode = (int)code;
52+
return context.Response.WriteAsync(result);
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)