Files
HTCloud/HT.Cloud.Code/Filter/GlobalExceptionMiddleware.cs
2023-03-03 16:07:50 +08:00

47 lines
1.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Threading.Tasks;
namespace HT.Cloud.Code
{
/// <summary>
/// 全局异常中间件api使用
/// </summary>
public class GlobalExceptionMiddleware
{
private readonly RequestDelegate next;
public GlobalExceptionMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context /* other dependencies */)
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var code = HttpStatusCode.OK;
LogHelper.WriteWithTime(exception);
var result = JsonConvert.SerializeObject(new AlwaysResult
{
state = ResultType.error.ToString(),
message = exception.Message
});
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);
}
}
}