消防站文档解析
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.3 KiB

2 years ago
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Infrastructure.Api.Middwares
{
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionMiddleware> _logger;
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception e)
{
await ExceptionHandlerAsync(context, e);
}
}
private async Task ExceptionHandlerAsync(HttpContext context, Exception ex)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = StatusCodes.Status200OK;
_logger?.LogError($"系统出现错误:{ex.Message}--{ex.StackTrace}");
var result = new CommonResponse { Code = context.Response.StatusCode.ToString(), Success = false, Message = ex.Message };
await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
}
}
}