1
This commit is contained in:
66
Gatedge.ScanCode/Middleware/GlobalExceptionMiddleware.cs
Normal file
66
Gatedge.ScanCode/Middleware/GlobalExceptionMiddleware.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
using Gatedge.K3Cloud.Utils.Exceptions;
|
||||
using Gatedge.ScanCode.Common;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Gatedge.ScanCode.Middleware
|
||||
{
|
||||
/// <summary>
|
||||
/// 自定义异常中间件
|
||||
/// </summary>
|
||||
public class GlobalExceptionMiddleware
|
||||
{
|
||||
/// <summary>
|
||||
/// 委托
|
||||
/// </summary>
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ILogger<GlobalExceptionMiddleware> _logger;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 构造方法
|
||||
/// </summary>
|
||||
/// <param name="next"></param>
|
||||
/// <param name="logger"></param>
|
||||
public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger)
|
||||
{
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 拦截请求
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <returns></returns>
|
||||
public async Task Invoke(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _next(context);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var result = AjaxResult.Error(500, ex.Message);
|
||||
var errTitle = ex.Message;
|
||||
var errInfo = ex.Message;
|
||||
if (ex is K3CloudException)
|
||||
{
|
||||
K3CloudException k3ViewException = (K3CloudException)ex;
|
||||
result = AjaxResult.Error(ex.Message);
|
||||
result.Add("error", k3ViewException.responseStatus.Errors);
|
||||
errInfo = JsonSerializer.Serialize(k3ViewException.responseStatus.Errors);
|
||||
}
|
||||
var errMessage = @$"
|
||||
=================================================
|
||||
errTitle: {errTitle}
|
||||
errInfo: {errInfo}
|
||||
=================================================
|
||||
";
|
||||
_logger.LogError(errMessage);
|
||||
context.Response.ContentType = "application/problem+json";
|
||||
var stream = context.Response.Body;
|
||||
await JsonSerializer.SerializeAsync(stream, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user