9 changed files with 16 additions and 296 deletions
-
2src/Shentun.Peis.Application.Contracts/CustomerOrgs/UpdateCustomerOrgDto.cs
-
102src/Shentun.Peis.HttpApi.Host/ErrorHandlerMiddleWare.cs
-
3src/Shentun.Peis.HttpApi.Host/Filter/ApplicationDescription.cs
-
0src/Shentun.Peis.HttpApi.Host/Filter/AuthorizationMiddlewareResultHandler.cs
-
5src/Shentun.Peis.HttpApi.Host/Filter/CustomerActionFilterAttribute.cs
-
9src/Shentun.Peis.HttpApi.Host/Filter/CustomerExceptionFilterAttribute.cs
-
4src/Shentun.Peis.HttpApi.Host/PeisHttpApiHostModule.cs
-
111src/Shentun.Peis.HttpApi.Host/PlanExceptionAttribute.cs
-
76src/Shentun.Peis.HttpApi.Host/WebApiExceptionFilterAttribute.cs
@ -1,102 +0,0 @@ |
|||||
using Microsoft.AspNetCore.Http.Features; |
|
||||
using Microsoft.AspNetCore.Http; |
|
||||
using Microsoft.Net.Http.Headers; |
|
||||
using System.Net; |
|
||||
using System.Text.Encodings.Web; |
|
||||
using System.Text.Json; |
|
||||
using System.Text.Unicode; |
|
||||
using System; |
|
||||
using System.Threading.Tasks; |
|
||||
using Microsoft.IdentityModel.Logging; |
|
||||
|
|
||||
namespace Shentun.Peis |
|
||||
{ |
|
||||
public class ErrorHandlerMiddleWare |
|
||||
{ |
|
||||
//请求委托
|
|
||||
private readonly RequestDelegate _next; |
|
||||
|
|
||||
// private readonly LogHelper _nlogger;
|
|
||||
|
|
||||
public ErrorHandlerMiddleWare(RequestDelegate next |
|
||||
//, LogHelper nlogger
|
|
||||
) |
|
||||
{ |
|
||||
this._next = next; |
|
||||
// this._nlogger = nlogger;
|
|
||||
} |
|
||||
|
|
||||
public async Task Invoke(HttpContext context) |
|
||||
{ |
|
||||
try |
|
||||
{ |
|
||||
await this._next.Invoke(context); |
|
||||
} |
|
||||
catch (Exception ex) |
|
||||
{ |
|
||||
await HandleExceptionAsync(context, ex); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
private async Task HandleExceptionAsync(HttpContext context, Exception exception) |
|
||||
{ |
|
||||
if (exception == null) return; |
|
||||
await HandleErrorResultAsync(context, exception).ConfigureAwait(false); |
|
||||
} |
|
||||
|
|
||||
private async Task HandleErrorResultAsync(HttpContext context, Exception exception) |
|
||||
{ |
|
||||
//记录日志
|
|
||||
// _nlogger.LogError(exception);
|
|
||||
//返回友好的提示
|
|
||||
var response = context.Response; |
|
||||
//清除原有HTTP上下文信息,为了明确指定程序出现异常,防止异常未被处理而后续当做正常操作执行
|
|
||||
ClearHttpContext(context); |
|
||||
//状态码
|
|
||||
if (exception is UnauthorizedAccessException) |
|
||||
response.StatusCode = (int)HttpStatusCode.Unauthorized; |
|
||||
else if (exception is BadHttpRequestException) |
|
||||
response.StatusCode = (int)HttpStatusCode.BadRequest; |
|
||||
else if (response.StatusCode == 403 || response.StatusCode == 404) { } |
|
||||
else response.StatusCode = (int)HttpStatusCode.InternalServerError; |
|
||||
|
|
||||
response.ContentType = context.Request.Headers["Accept"]; |
|
||||
var result = new ApiResult |
|
||||
{ |
|
||||
Code = 500, |
|
||||
Message = exception.GetBaseException().Message |
|
||||
}; |
|
||||
if (response.ContentType.ToLower() != "application/x-www-form-urlencoded") |
|
||||
{ |
|
||||
response.ContentType = "application/json"; |
|
||||
} |
|
||||
await response.WriteAsync(JsonSerializer.Serialize(result |
|
||||
, new JsonSerializerOptions() |
|
||||
{ |
|
||||
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All), |
|
||||
PropertyNameCaseInsensitive = true, |
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase |
|
||||
})).ConfigureAwait(false); |
|
||||
} |
|
||||
|
|
||||
private static void ClearHttpContext(HttpContext context) |
|
||||
{ |
|
||||
context.Response.Clear(); |
|
||||
//因为可能创建了新的终结点,所以执行管道会有所调整,所以需要重新计算
|
|
||||
context.SetEndpoint(endpoint: null); |
|
||||
var routeValuesFeature = context.Features.Get<IRouteValuesFeature>(); |
|
||||
routeValuesFeature?.RouteValues?.Clear(); |
|
||||
} |
|
||||
|
|
||||
private static Task ClearCacheHeaders(object state) |
|
||||
{ |
|
||||
//清除输出缓存相关
|
|
||||
var headers = ((HttpResponse)state).Headers; |
|
||||
headers[HeaderNames.CacheControl] = "no-cache"; |
|
||||
headers[HeaderNames.Pragma] = "no-cache"; |
|
||||
headers[HeaderNames.Expires] = "-1"; |
|
||||
headers.Remove(HeaderNames.ETag); |
|
||||
return Task.CompletedTask; |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
@ -1,111 +0,0 @@ |
|||||
using Microsoft.AspNetCore.Mvc; |
|
||||
using Microsoft.AspNetCore.Mvc.Filters; |
|
||||
using Microsoft.Extensions.Logging; |
|
||||
|
|
||||
namespace Shentun.Peis |
|
||||
{ |
|
||||
public class PlanExceptionAttribute |
|
||||
{ |
|
||||
//private readonly ILogger<PlanExceptionAttribute> _logger;
|
|
||||
|
|
||||
|
|
||||
///// <summary>
|
|
||||
/////
|
|
||||
///// </summary>
|
|
||||
///// <param name="context"></param>
|
|
||||
//public override void OnException(ExceptionContext context)
|
|
||||
//{
|
|
||||
|
|
||||
// // 如果异常没有被处理则进行处理
|
|
||||
// if (context.ExceptionHandled == false)
|
|
||||
// {
|
|
||||
// var userExpect = context.Exception as OnlineContractException;
|
|
||||
// var info = new ExceptionModel();
|
|
||||
// info.code = "500";
|
|
||||
// info.success = false;
|
|
||||
// info.message = "服务器遇到一个错误,无法继续为您服务!";
|
|
||||
|
|
||||
// if (userExpect != null)
|
|
||||
// {
|
|
||||
// info.code = $"{userExpect.Code}";
|
|
||||
// info.message = context.Exception.Message;
|
|
||||
// }
|
|
||||
// else
|
|
||||
// {
|
|
||||
// var volexception = context.Exception as OnlineContractException;
|
|
||||
// if (volexception != null)
|
|
||||
// {
|
|
||||
// info.code = $"{volexception.Code}";
|
|
||||
// info.message = volexception.Message;
|
|
||||
// }
|
|
||||
// }
|
|
||||
// if (context.ModelState != null)
|
|
||||
// {
|
|
||||
// if (context.ModelState.Count > 0)
|
|
||||
// {
|
|
||||
// foreach (var key in context.ModelState.Keys)
|
|
||||
// {
|
|
||||
// context.ModelState.TryGetValue(key, out var val);
|
|
||||
// if (val.Errors.Count > 0)
|
|
||||
// {
|
|
||||
// info.message = key + "::" + val.Errors[0].ErrorMessage;
|
|
||||
// break;
|
|
||||
// }
|
|
||||
// }
|
|
||||
// }
|
|
||||
// }
|
|
||||
|
|
||||
// if (info.code == "500")
|
|
||||
// {
|
|
||||
// //写入日志
|
|
||||
// _logger.LogError(context.Exception, context.HttpContext.Request.Path, null);
|
|
||||
|
|
||||
// }
|
|
||||
|
|
||||
|
|
||||
// context.Result = new ContentResult
|
|
||||
// {
|
|
||||
// // 返回状态码设置为200,表示成功
|
|
||||
// StatusCode = int.Parse(info.code),
|
|
||||
// // 设置返回格式
|
|
||||
// ContentType = "application/json;charset=utf-8",
|
|
||||
// Content = Newtonsoft.Json.JsonConvert.SerializeObject(info)
|
|
||||
// };
|
|
||||
// }
|
|
||||
// // 设置为true,表示异常已经被处理了
|
|
||||
// context.ExceptionHandled = true;
|
|
||||
|
|
||||
//}
|
|
||||
|
|
||||
|
|
||||
///// <summary>
|
|
||||
/////
|
|
||||
///// </summary>
|
|
||||
///// <param name="context"></param>
|
|
||||
///// <returns></returns>
|
|
||||
//public override System.Threading.Tasks.Task OnExceptionAsync(ExceptionContext context)
|
|
||||
//{
|
|
||||
// return base.OnExceptionAsync(context);
|
|
||||
//}
|
|
||||
|
|
||||
} |
|
||||
|
|
||||
/// <summary>
|
|
||||
///
|
|
||||
/// </summary>
|
|
||||
public class ExceptionModel |
|
||||
{ |
|
||||
/// <summary>
|
|
||||
///
|
|
||||
/// </summary>
|
|
||||
public string code { get; set; } |
|
||||
/// <summary>
|
|
||||
///
|
|
||||
/// </summary>
|
|
||||
public bool success { get; set; } |
|
||||
/// <summary>
|
|
||||
///
|
|
||||
/// </summary>
|
|
||||
public string message { get; set; } |
|
||||
} |
|
||||
} |
|
||||
@ -1,76 +0,0 @@ |
|||||
using Microsoft.AspNetCore.Mvc; |
|
||||
using Microsoft.AspNetCore.Mvc.Filters; |
|
||||
using Microsoft.EntityFrameworkCore; |
|
||||
using Microsoft.Extensions.Logging; |
|
||||
using Shentun.Utilities; |
|
||||
using Shentun.WebApi.Service; |
|
||||
using System; |
|
||||
using System.Data.SqlClient; |
|
||||
using System.Net; |
|
||||
using System.Net.Http; |
|
||||
using Volo.Abp; |
|
||||
using Volo.Abp.AspNetCore.ExceptionHandling; |
|
||||
|
|
||||
namespace Shentun.Peis |
|
||||
{ |
|
||||
public class WebApiExceptionFilterAttribute : Microsoft.AspNetCore.Mvc.Filters.ExceptionFilterAttribute |
|
||||
{ |
|
||||
private readonly ILogger<WebApiExceptionFilterAttribute> _logger; |
|
||||
public WebApiExceptionFilterAttribute(ILogger<WebApiExceptionFilterAttribute> logger) |
|
||||
{ |
|
||||
_logger = logger; |
|
||||
} |
|
||||
//重写基类的异常处理方法
|
|
||||
public override void OnException(ExceptionContext exceptionContext) |
|
||||
{ |
|
||||
Console.WriteLine("WebApiExceptionFilter.OnException"); |
|
||||
var objectResult = exceptionContext.Result as ObjectResult; |
|
||||
//异常日志记录
|
|
||||
string error = string.Empty; |
|
||||
ReadException(exceptionContext.Exception, ref error); |
|
||||
//LogHelper.Logger.LogError(error);
|
|
||||
_logger.LogError("异常:" + error+ Environment.NewLine + "异常堆栈:" +exceptionContext.Exception.StackTrace |
|
||||
); |
|
||||
//处理异常信息
|
|
||||
|
|
||||
string errorMessage; |
|
||||
|
|
||||
if (exceptionContext.Exception is DbUpdateException) |
|
||||
{ |
|
||||
errorMessage = "数据库更新错误:" + exceptionContext.Exception.Message; |
|
||||
} |
|
||||
else if (exceptionContext.Exception is BusinessException) |
|
||||
{ |
|
||||
|
|
||||
errorMessage = "业务错误:" + exceptionContext.Exception.Message; |
|
||||
} |
|
||||
else if (exceptionContext.Exception is ArgumentNullException) |
|
||||
{ |
|
||||
|
|
||||
errorMessage = exceptionContext.Exception.Message; |
|
||||
} |
|
||||
else if(exceptionContext.Exception is ArgumentException) |
|
||||
{ |
|
||||
|
|
||||
errorMessage = exceptionContext.Exception.Message; |
|
||||
} |
|
||||
else |
|
||||
{ |
|
||||
errorMessage = exceptionContext.Exception.Message; |
|
||||
} |
|
||||
|
|
||||
exceptionContext.Result = new JsonResult(ReturnValue.CreateErrorInstance(errorMessage)); |
|
||||
exceptionContext.Exception = null; |
|
||||
//base.OnException(exceptionContext);
|
|
||||
} |
|
||||
|
|
||||
private void ReadException(Exception ex,ref string error) |
|
||||
{ |
|
||||
error += string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException); |
|
||||
if (ex.InnerException != null) |
|
||||
{ |
|
||||
ReadException(ex.InnerException,ref error); |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
Write
Preview
Loading…
Cancel
Save
Reference in new issue