docker files fixes from liaqat
This commit is contained in:
62
src/Managing.Api/Exceptions/GlobalErrorHandlingMiddleware.cs
Normal file
62
src/Managing.Api/Exceptions/GlobalErrorHandlingMiddleware.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Managing.Api.Exceptions;
|
||||
|
||||
public class GlobalErrorHandlingMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
public GlobalErrorHandlingMiddleware(RequestDelegate next)
|
||||
{
|
||||
_next = next;
|
||||
}
|
||||
public async Task Invoke(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _next(context);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await HandleExceptionAsync(context, ex);
|
||||
}
|
||||
}
|
||||
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
|
||||
{
|
||||
HttpStatusCode status;
|
||||
var exceptionType = exception.GetType();
|
||||
|
||||
if (exceptionType == typeof(Exception))
|
||||
{
|
||||
status = HttpStatusCode.InternalServerError;
|
||||
}
|
||||
else if (exceptionType == typeof(NotImplementedException))
|
||||
{
|
||||
status = HttpStatusCode.NotImplemented;
|
||||
}
|
||||
else if (exceptionType == typeof(UnauthorizedAccessException))
|
||||
{
|
||||
status = HttpStatusCode.Unauthorized;
|
||||
}
|
||||
else if (exceptionType == typeof(ArgumentException))
|
||||
{
|
||||
status = HttpStatusCode.Unauthorized;
|
||||
}
|
||||
else if (exceptionType == typeof(KeyNotFoundException))
|
||||
{
|
||||
status = HttpStatusCode.Unauthorized;
|
||||
}
|
||||
else
|
||||
{
|
||||
status = HttpStatusCode.InternalServerError;
|
||||
}
|
||||
|
||||
var message = exception.Message;
|
||||
var stackTrace = exception.StackTrace;
|
||||
var exceptionResult = JsonSerializer.Serialize(new { error = message, stackTrace });
|
||||
|
||||
context.Response.ContentType = "application/json";
|
||||
context.Response.StatusCode = (int)status;
|
||||
return context.Response.WriteAsync(exceptionResult);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user