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.

77 lines
2.5 KiB
C#

11 months ago
using Common.Utilities;
using djy.Model;
11 months ago
using Microsoft.AspNetCore.Http;
11 months ago
using Microsoft.Extensions.Logging;
11 months ago
using Newtonsoft.Json;
using System;
using System.Net;
using System.Threading.Tasks;
namespace djy_AfrApi.Middlewares
{
public class ExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;
11 months ago
private readonly ILogger<ExceptionHandlerMiddleware> logger;
11 months ago
11 months ago
public ExceptionHandlerMiddleware(RequestDelegate next, ILogger<ExceptionHandlerMiddleware> logger)
11 months ago
{
_next = next;
11 months ago
this.logger = logger;
11 months ago
}
public async Task Invoke(HttpContext context)
{
try
{
11 months ago
//_ = int.Parse("");
11 months ago
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception e)
{
if (e == null) return;
11 months ago
11 months ago
logger.LogError(WriteLog("ExceptionHandlerMiddleware中捕获的全局异常", e));
11 months ago
await WriteExceptionAsync(context, e).ConfigureAwait(false);
}
private static async Task WriteExceptionAsync(HttpContext context, Exception e)
{
var message = e.Message;
switch (e)
{
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
11 months ago
.WriteAsync(JsonConvert.SerializeObject(new Response() { Code = 500, Message = message }))
11 months ago
.ConfigureAwait(false);
}
11 months ago
/// <summary>
/// 自定义返回格式
/// </summary>
/// <param name="throwMsg"></param>
/// <param name="ex"></param>
/// <returns></returns>
public string WriteLog(string throwMsg, Exception ex)
{
return string.Format("\r\n【自定义错误】{0} \r\n【异常类型】{1} \r\n【异常信息】{2} \r\n【堆栈调用】{3}\r\n自定义异常结束", new object[] { throwMsg,
ex.GetType().Name, ex.Message, ex.StackTrace });
}
11 months ago
}
}