2019-12-23 16:32:06 +08:00
|
|
|
using System;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using Microsoft.AspNetCore.Http;
|
2020-08-05 15:29:56 +08:00
|
|
|
using SimApi.Communications;
|
2019-12-23 16:32:06 +08:00
|
|
|
using Microsoft.Extensions.Logging;
|
2020-08-05 15:29:56 +08:00
|
|
|
using SimApi.Exceptions;
|
2019-12-23 16:32:06 +08:00
|
|
|
|
2020-08-05 15:29:56 +08:00
|
|
|
namespace SimApi.Middlewares
|
2019-12-23 16:32:06 +08:00
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 异常处理中间件
|
|
|
|
|
/// </summary>
|
2020-08-05 15:29:56 +08:00
|
|
|
public class SimApiExceptionMiddleware
|
2019-12-23 16:32:06 +08:00
|
|
|
{
|
|
|
|
|
private RequestDelegate Next { get; }
|
2020-08-05 15:29:56 +08:00
|
|
|
private ILogger<SimApiExceptionMiddleware> Log { get; }
|
2019-12-23 16:32:06 +08:00
|
|
|
|
2020-08-05 15:29:56 +08:00
|
|
|
public SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExceptionMiddleware> log)
|
2019-12-23 16:32:06 +08:00
|
|
|
{
|
|
|
|
|
Log = log;
|
|
|
|
|
Next = next;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
|
|
|
{
|
2020-08-29 11:49:44 +08:00
|
|
|
if (context.Request.Headers.ContainsKey("Query-Id"))
|
|
|
|
|
{
|
|
|
|
|
context.Response.Headers["Query-Id"] = context.Request.Headers["Query-Id"];
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-05 15:29:56 +08:00
|
|
|
var response = new SimApiBaseResponse();
|
2019-12-23 16:32:06 +08:00
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await Next(context);
|
|
|
|
|
}
|
2020-08-05 15:29:56 +08:00
|
|
|
catch (SimApiException ex)
|
2019-12-23 16:32:06 +08:00
|
|
|
{
|
2020-08-23 21:42:41 +08:00
|
|
|
if (string.IsNullOrEmpty(ex.Message))
|
|
|
|
|
{
|
|
|
|
|
response.SetCode(ex.Code);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
response.SetCodeMsg(ex.Code, ex.Message);
|
|
|
|
|
}
|
2019-12-23 16:32:06 +08:00
|
|
|
ErrorResponse(context, response);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
Log.LogError(ex.Message);
|
|
|
|
|
Log.LogError(ex.StackTrace);
|
|
|
|
|
response.SetCodeMsg(500, ex.Message);
|
|
|
|
|
ErrorResponse(context, response);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 异常抛出错误
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="context"></param>
|
|
|
|
|
/// <param name="response"></param>
|
2020-08-05 15:29:56 +08:00
|
|
|
private void ErrorResponse(HttpContext context, SimApiBaseResponse response)
|
2019-12-23 16:32:06 +08:00
|
|
|
{
|
|
|
|
|
context.Response.StatusCode = 200;
|
|
|
|
|
context.Response.Headers.Add("Content-Type", "application/json");
|
|
|
|
|
context.Response.WriteAsync(response.ToString());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|