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.
68 lines
1.9 KiB
C#
68 lines
1.9 KiB
C#
using Ds.WMS.MogonDb.Commond;
|
|
using Ds.WMS.WebCore.exception;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Newtonsoft.Json;
|
|
using System.Net;
|
|
|
|
namespace Ds.WMS.WebCore.applog
|
|
{
|
|
public class GlobalExceptionHandler
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
|
|
public GlobalExceptionHandler(RequestDelegate next)
|
|
{
|
|
_next = next;
|
|
}
|
|
|
|
public async Task Invoke(HttpContext context)
|
|
{
|
|
try
|
|
{
|
|
await _next(context);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await HandleExceptionAsync(context, ex);
|
|
}
|
|
}
|
|
|
|
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
|
|
{
|
|
var code = HttpStatusCode.InternalServerError;
|
|
var message = ex.Message;
|
|
|
|
if (ex is UnauthorizedAccessException)
|
|
{
|
|
code = HttpStatusCode.Unauthorized;
|
|
message = "没有权限";
|
|
}
|
|
else if (ex is NotFoundException)
|
|
{
|
|
code = HttpStatusCode.NotFound;
|
|
message = "没有数据";
|
|
}
|
|
else if (ex is BadRequestException)
|
|
{
|
|
code = HttpStatusCode.BadRequest;
|
|
message = "操作失败";
|
|
}
|
|
|
|
var result = JsonConvert.SerializeObject(new { error = message });
|
|
context.Response.ContentType = "application/json";
|
|
context.Response.StatusCode = (int)code;
|
|
|
|
// 创建一个错误日志实体并保存到数据库
|
|
var errorLog = new CostErrorLogCommand
|
|
{
|
|
StatusCode = context.Response.StatusCode,
|
|
ErrorMessage = ex.Message,
|
|
StackTrace = ex.StackTrace,
|
|
// 设置其他属性...
|
|
TimeStamp = DateTime.UtcNow
|
|
};
|
|
|
|
return context.Response.WriteAsync(result);
|
|
}
|
|
}
|
|
} |