- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 .NET 4.6.1 上有一个传统的 WebApi 项目,它有一个全局 ExceptionFilter
,它处理已知异常以返回带有相应状态代码的友好消息。
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Filters.Add(new MyExceptionFilterAttribute());
}
MyExceptionFilterAttribute.cs
internal sealed class GatewayExceptionFilterAttribute : ExceptionFilterAttribute
{
private static readonly Dictionary<Type, HttpStatusCode> Exceptions = new Dictionary<Type, HttpStatusCode>
{
// HTTP 400
[typeof(ArgumentException)] = HttpStatusCode.BadRequest,
[typeof(ArgumentNullException)] = HttpStatusCode.BadRequest,
};
public override void OnException(HttpActionExecutedContext context)
{
var type = context.Exception.GetType();
if (context.Exception is HttpResponseException)
return;
// Return 500 for unspecified errors
var status = HttpStatusCode.InternalServerError;
var message = Strings.ERROR_INTERNAL_ERROR;
if (Exceptions.ContainsKey(type))
{
status = Exceptions[type];
message = context.Exception.Message;
}
context.Response = context.Request.CreateErrorResponse(status, message);
}
}
MyController.cs
public class MyController : ApiController
{
public async Task<IHttpActionResult> Get()
{
await Task.Run(() => { throw new ArgumentNullException("Error"); });
return Ok();
}
}
按原样调用时,我将收到 400
。
但是,当添加对 .NETStandard 2.0 库的引用时,异常不会转到 ExceptionFilter
并且我收到以下错误:
{
"message": "An error has occurred.",
"exceptionMessage": "Method not found: 'System.Net.Http.HttpRequestMessage System.Web.Http.Filters.HttpActionExecutedContext.get_Request()'.",
"exceptionType": "System.MissingMethodException",
"stackTrace": " at MyApi.Filters.MyExceptionFilterAttribute.OnException(HttpActionExecutedContext context)\r\n at System.Web.Http.Filters.ExceptionFilterAttribute.OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.ExceptionFilterAttribute.<ExecuteExceptionFilterAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}
感谢任何帮助。
最佳答案
我在使用 .Net 4.6.2 Web API 时遇到了同样的问题。我在 Web 项目中定义了以下异常处理程序:
public class ExceptionHandlerAttribute : ExceptionFilterAttribute
{
private readonly MyLogger _logger;
private const string ExceptionOccuredLoggingTag = "ExceptionOccured";
public ExceptionHandlerAttribute(MyLogger logger)
{
_logger = logger;
}
public override void OnException(HttpActionExecutedContext context)
{
...
_logger.Error(errorMessage,
context.Exception,
mostRecentFrame.Class.Name,
mostRecentFrame.Method.Name,
ExceptionOccuredLoggingTag);
...
}
}
在另一个 .NETStandart 2.0 dll 中定义了 MyLogger
类。在尝试调用它时,它向我显示了与上面相同的异常。
这里对我有用的解决方法是在 Web 项目引用的另一个库(非 .NETStandart 2.0)中定义一个 .Net 框架适配器 MyLoggerAdapter
(在我的例子中是业务层库):
public interface ILoggerCompatable
{
void Error(string message, object data, params string[] tags);
}
public class MyLoggerAdapter : ILoggerCompatable
{
private readonly MyLogger _logger;
public MyLoggerAdapter(MyLogger logger)
{
_logger = logger;
}
public void Error(string message, object data, params string[] tags) => _logger.Error(message, data, tags.Select(tag => (Tag)tag).ToArray());
}
因此从源 .NETStandart 库中看不到任何内容,然后将其注入(inject)处理程序(通过 Autofac):
public class ExceptionHandlerAttribute : ExceptionFilterAttribute
{
private readonly ILoggerCompatable _logger;
private const string ExceptionOccuredLoggingTag = "ExceptionOccured";
public ExceptionHandlerAttribute(ILoggerCompatable logger)
{
_logger = logger;
}
public override void OnException(HttpActionExecutedContext context)
{
...
_logger.Error(errorMessage,
context.Exception,
mostRecentFrame.Class.Name,
mostRecentFrame.Method.Name,
ExceptionOccuredLoggingTag);
...);
}
}
过滤器注册看起来像这样:
var loggerCompatable = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(ILoggerCompatable)) as ILoggerCompatable;
GlobalConfiguration.Configuration.Filters.Add(new ExceptionHandlerAttribute(loggerCompatable));
希望这对您有所帮助!
关于c# - 引用标准库后异常不会进入 ExceptionFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48589767/
我最近在读 CSAPP。在 10.9 节中,它说标准 I/O 不应该与 socket 一起使用,原因如下: (1) The restrictions of standard I/O Restricti
似乎是一个足够标准的问题,可以保证解决方案中的标准设计: 假设我想在文件中写入 x+2(或更少)个字符串。 x 字符串构成一个部分的内容,这两个字符串构成该部分的页眉和页脚。要注意的是,如果内容中没有
代码版本管理 在项目中,代码的版本管理非常重要。每个需求版本的代码开发在版本控制里都应该经过以下几个步骤。 在master分支中拉取该需求版本的两个分支,一个feature分支,
我有以下sql查询,我需要获取相应的hibernate条件查询 SELECT COUNT(DISTINCT employee_id) FROM erp_hr_payment WHERE payment
所以我正在编写一些代码,并且最近遇到了实现一些 mixin 的需要。我的问题是,设计混音的正确方法是什么?我将使用下面的示例代码来说明我的确切查询。 class Projectile(Movable,
我的环境变量包含如下双引号: $echo $CONNECT_SASL_JAAS_CONFIG org.apache.kafka.common.security.plain.PlainLoginModu
示例: /** * This function will determine whether or not one string starts with another string. * @pa
有没有办法在 Grails 中做一个不区分大小写的 in 子句? 我有这个: "in"("name", filters.tags) 我希望它忽略大小写。我想我可以做一个 sqlRestriction
我搜索了很长时间,以查找将哪些boost库添加到std库中,但是我只找到了一个新库的完整列表(如此处:http://open-std.org/jtc1/sc22/wg21/docs/library_t
我已经通过使用这个肮脏的黑客解决了我的问题: ' Filter managerial functions ActiveSheet.Range("$A$1:$BW$2211").Auto
因此,我很难理解我需要遵循的标准,以便我的 Java 程序能够嵌入 HTML。我是否只需将我的主类扩展到 Applet 类,或者我还需要做更多的事情吗?另外,在我见过的每个 Applet 示例中,它都
我对在 Hibernate 中使用限制有疑问。 我必须创建条件,设置一些限制,然后选择日期字段最大值的记录: Criteria query = session.createCriteria(Stora
我有标准: ICriteria criteria = Session.CreateCriteria() .SetFetchMode("Entity1", FetchMo
我很难编写条件来选择所有子集合或孙集合为空的实体。我可以将这些作为单独的条件来执行,但我无法将其组合成一个条件。 类结构: public class Component { p
@Entity class A { @ManyToMany private List list; ... } @Entity class B { ... } 我想使用条件(不是 sql 查询)从 A
我的数据库中有以下表结构: Table A: Table B: Table C: _______________
请帮助我: 我有下一张 table : 单位 ID 姓名 用户 ID 姓名 利率 单位 ID 用户 ID 我不明白如何从 SQL 创建正确的条件结构: 代码: SELECT * FROM Unit W
我正在构建一个包含项目的网站,每个项目都有一个页面,例如: website.com/book/123 website.com/film/456 website.com/game/789 每个项目都可以
我需要使用两个属性的组合来过滤结果列表。一个简单的 SQL 语句如下所示: SELECT TOP 10 * FROM Person WHERE FirstName + ' ' + LastName L
我有一个“ super 实体”SuperEntity 和三个扩展父类(super class)的实体 ChildEntity1、...、ChildEntity3。 搜索数据库中的所有实体很容易,即我们
我是一名优秀的程序员,十分优秀!