12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- using System;
- using System.Threading.Tasks;
- using Luticate2.Utils.Controllers;
- using Luticate2.Utils.Dbo.Basic;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Options;
- using Newtonsoft.Json;
-
- namespace Luticate2.Utils.Middlewares
- {
- public class LuExceptionMiddleware
- {
- private readonly RequestDelegate _next;
- private readonly ILogger<LuExceptionMiddleware> _logger;
- private readonly LuUtilsOptionsDbo _luUtilsOptionsDbo;
-
- public LuExceptionMiddleware(RequestDelegate next, ILogger<LuExceptionMiddleware> logger, IOptions<LuUtilsOptionsDbo> luUtilsOptionsDbo)
- {
- _next = next;
- _logger = logger;
- _luUtilsOptionsDbo = luUtilsOptionsDbo.Value;
- }
-
- public async Task Invoke(HttpContext context)
- {
- try
- {
- await _next.Invoke(context);
- }
- catch (LuResultException e)
- {
- _logger.LogError(e.Result.PrivateDetails + "\n" + e.Result.PublicDetails + "\n" + e.StackTrace);
- var response = context.Response;
- response.ContentType = "application/json";
- response.StatusCode = e.Result.GetHttpCode();
- await response.WriteAsync(JsonConvert.SerializeObject(new LuApiWrapperDbo<object>
- {
- code = e.Result.GetHttpCode(),
- data = null,
- message = e.Result.PublicDetails ?? e.Result.GetHttpString(),
- version = _luUtilsOptionsDbo.Version
- })).ConfigureAwait(false);
- }
- catch (Exception e)
- {
- _logger.LogError(e.ToString());
- var response = context.Response;
- response.ContentType = "application/json";
- response.StatusCode = 500;
- await response.WriteAsync(JsonConvert.SerializeObject(new LuApiWrapperDbo<object>
- {
- code = 500,
- data = null,
- message = "Internal Error",
- version = _luUtilsOptionsDbo.Version
- })).ConfigureAwait(false);
- }
- }
- }
- }
|