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.

76 lines
2.5 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using Common.Utilities;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Threading.Tasks;
namespace djy_AfrApi.Middlewares
{
public class ExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlerMiddleware> logger;
public ExceptionHandlerMiddleware(RequestDelegate next, ILogger<ExceptionHandlerMiddleware> logger)
{
_next = next;
this.logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
//_ = int.Parse("");
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception e)
{
if (e == null) return;
logger.LogError(WriteLog($"ExceptionHandlerMiddleware中捕获的全局异常TraceIdentifier{context.TraceIdentifier}", e));
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
.WriteAsync(JsonConvert.SerializeObject(new Response() { Code = 500, Message = message }))
.ConfigureAwait(false);
}
/// <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 });
}
}
}