using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Mvc;
|
using System.Threading.Tasks;
|
using System;
|
using System.Text.Json;
|
using Microsoft.AspNetCore.Builder;
|
using Microsoft.Extensions.Logging;
|
using Utility.Entity;
|
using Newtonsoft.Json;
|
using System.Text;
|
|
namespace Utility
|
{
|
public class CustomerExceptionMiddleware
|
{
|
private readonly RequestDelegate _next;
|
private readonly ILogger<CustomerExceptionMiddleware> _logger;
|
|
public CustomerExceptionMiddleware(RequestDelegate next, ILogger<CustomerExceptionMiddleware> logger)
|
{
|
_next = next;
|
_logger = logger;
|
}
|
|
public async Task Invoke(HttpContext context)
|
{
|
try
|
{
|
await _next(context);
|
}
|
catch (Exception ex)
|
{
|
_logger.LogError(ex, ex.Message);
|
context.Response.ContentType = "application/json";
|
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
var result = "系统异常,请联系管理员";
|
if (ex is AppFriendlyException)
|
result = ex.Message;
|
var apiResponse = new ApiResponse<object>(
|
code: (int)ResponseEnum.Error,
|
message: result,
|
data: result
|
);
|
var json = JsonConvert.SerializeObject(apiResponse);
|
context.Response.ContentType = "application/json";
|
context.Response.ContentLength = Encoding.UTF8.GetByteCount(json);
|
await context.Response.WriteAsync(json);
|
}
|
}
|
}
|
|
/// <summary>
|
/// 静态类
|
/// </summary>
|
public static class ExceptionMiddlewareExtension
|
{
|
/// <summary>
|
/// 静态方法
|
/// </summary>
|
/// <param name="app">要进行扩展的类型</param>
|
public static void UseExceptionMiddleware(this IApplicationBuilder app)
|
{
|
app.UseMiddleware(typeof(CustomerExceptionMiddleware));
|
}
|
}
|
}
|