Ai
1 Star 0 Fork 0

liming/Scheduler

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ExceptionMiddleware.cs 1.59 KB
一键复制 编辑 原始数据 按行查看 历史
liming 提交于 2025-04-21 14:55 +08:00 . 增加NLog.Extensions.Logging方式
using Newtonsoft.Json;
using System.Net;
using Scheduler.Model;
using Scheduler.Common.Helper;
namespace Scheduler.WebAPI
{
/// <summary>
/// 异常处理中间件
/// </summary>
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly IHostEnvironment _environment;
private readonly ILogger<ExceptionMiddleware> _logger;
public ExceptionMiddleware(RequestDelegate next, IHostEnvironment environment, ILogger<ExceptionMiddleware> logger)
{
_next = next;
_environment = environment;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
string errorMsg = $"错误消息:{exception.Message}{Environment.NewLine}错误追踪:{exception.StackTrace}";
_logger.LogError(errorMsg);
string message = _environment.IsDevelopment() ? exception.Message : "抱歉,服务端出错了!";
var errorResult = MessageModel<object>.ErrorResult(message);
return context.Response.WriteAsync(JsonConvert.SerializeObject(errorResult));
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/cplmlm/scheduler.git
git@gitee.com:cplmlm/scheduler.git
cplmlm
scheduler
Scheduler
master

搜索帮助