You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.3 KiB
C#
48 lines
1.3 KiB
C#
using EntrustSettle.Model;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Newtonsoft.Json;
|
|
using System;
|
|
using System.Net;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace EntrustSettle.Extensions.Middlewares
|
|
{
|
|
public class ExceptionHandlerMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
|
|
public ExceptionHandlerMiddleware(RequestDelegate next)
|
|
{
|
|
_next = next;
|
|
}
|
|
|
|
public async Task Invoke(HttpContext context)
|
|
{
|
|
try
|
|
{
|
|
await _next(context);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
if (ex == null) return;
|
|
|
|
var message = ex.Message;
|
|
switch (ex)
|
|
{
|
|
case UnauthorizedAccessException:
|
|
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
|
|
break;
|
|
default:
|
|
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
|
|
break;
|
|
}
|
|
|
|
context.Response.ContentType = "application/json";
|
|
|
|
await context.Response
|
|
.WriteAsync(JsonConvert.SerializeObject(new ApiResponse(StatusCode.CODE500, message).MessageModel))
|
|
.ConfigureAwait(false);
|
|
}
|
|
}
|
|
}
|
|
} |