/// <summary> /// 异常时 /// </summary> /// <param name="context"></param> public virtual void OnException(ExceptionContext context) { if (this.Enbale == false) { return; } var apiResultType = context.GetApiDescription() .SupportedResponseTypes .Select(item => item.Type) .Where(item => item.IsInheritFrom <IApiResult>()) .FirstOrDefault(); if (apiResultType == null) { apiResultType = typeof(ApiResult <object>); } var apiResult = Activator.CreateInstance(apiResultType) as IApiResult; apiResult.Message = context.Exception.Message; apiResult.Code = context.Exception is ArgumentException ? Code.ParameterError : Code.ServiceError; context.HttpContext .RequestServices .GetService <ILogger <ApiExceptionFilterAttribute> >() .LogError(context.Exception, context.Exception.Message); context.ExceptionHandled = true; context.Result = new ObjectResult(apiResult); }