2019-12-23 16:32:06 +08:00
|
|
|
using System;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
|
using YYApi.Communications;
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
2020-02-04 16:51:15 +08:00
|
|
|
using YYApi.Exceptions;
|
2019-12-23 16:32:06 +08:00
|
|
|
|
2020-02-04 16:51:15 +08:00
|
|
|
namespace YYApi.Middlewares
|
2019-12-23 16:32:06 +08:00
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 异常处理中间件
|
|
|
|
|
/// </summary>
|
2020-02-04 16:51:15 +08:00
|
|
|
public class YYExceptionMiddleware
|
2019-12-23 16:32:06 +08:00
|
|
|
{
|
|
|
|
|
private RequestDelegate Next { get; }
|
2020-02-04 16:51:15 +08:00
|
|
|
private ILogger<YYExceptionMiddleware> Log { get; }
|
2019-12-23 16:32:06 +08:00
|
|
|
|
2020-02-04 16:51:15 +08:00
|
|
|
public YYExceptionMiddleware(RequestDelegate next, ILogger<YYExceptionMiddleware> log)
|
2019-12-23 16:32:06 +08:00
|
|
|
{
|
|
|
|
|
Log = log;
|
|
|
|
|
Next = next;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
|
|
|
{
|
2020-02-04 16:51:15 +08:00
|
|
|
var response = new YYBaseResponse();
|
2019-12-23 16:32:06 +08:00
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await Next(context);
|
|
|
|
|
}
|
2020-02-04 16:51:15 +08:00
|
|
|
catch (YYApiException ex)
|
2019-12-23 16:32:06 +08:00
|
|
|
{
|
|
|
|
|
response.SetCodeMsg(ex.Code, ex.Message);
|
|
|
|
|
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-02-04 16:51:15 +08:00
|
|
|
private void ErrorResponse(HttpContext context, YYBaseResponse 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());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|