是否可以使用源发电机来处理异常?
我有一个接口:
Task DoStuff();
一个实现:
public async Task DoStuff()
{
await DoStuffAndThrowException();
}
是否有一种使用源代码生成器来处理异常的方法:
public async Task DoStuff()
{
try
{
await DoStuffAndThrowException();
}
catch (Exception exception)
{
throw new MySpecialException(exception);
}
}
或:
public async Task DoStuff()
{
await DoStuffAndThrowExceptionWrapped();
}
public async Task DoStuffAndThrowExceptionWrapped()
{
try
{
await DoStuffAndThrowException();
}
catch (Exception exception)
{
throw new MySpecialException(exception);
}
}
I have an interface:
Task DoStuff();
And an implementation:
public async Task DoStuff()
{
await DoStuffAndThrowException();
}
Is there a way to use source code generators in order to handle exceptions for example like:
public async Task DoStuff()
{
try
{
await DoStuffAndThrowException();
}
catch (Exception exception)
{
throw new MySpecialException(exception);
}
}
or:
public async Task DoStuff()
{
await DoStuffAndThrowExceptionWrapped();
}
public async Task DoStuffAndThrowExceptionWrapped()
{
try
{
await DoStuffAndThrowException();
}
catch (Exception exception)
{
throw new MySpecialException(exception);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不是源生成器的专家,但据我了解,它们没有修改现有方法:它们打算 add 生成的源。因此,它们非常适合您可能放入单独的
部分
类文件中的东西。您要做的事情将通过面向方面的编程框架更好地完成。后期是为这类事情制作的,但是它要花钱,但我没有使用过。 Fody Weaver库有一些免费的插件,可能可以帮助您完成所需的工作。例如, methodboundaryaspect.fody.fody 会让您创建一个属性,以改变方法输入的行为,退出和异常,然后您可以在特定方法,类中的所有方法或组件中的所有方法上应用这些属性。
I'm not an expert on Source Generators, but from what I've understood they don't modify existing methods: they're meant to add generated source. So they're good for the kinds of things you might put in a separate
partial
class file.What you're looking to do would be better accomplished by an aspect-oriented programming framework. Postsharp is made for these kinds of things, but it costs money and I haven't used it. There are some free plugins for the Fody Weaver library that can probably help you do what you're looking for. For example, MethodBoundaryAspect.Fody will let you create an attribute that alters the behaviors of method entry, exit, and exceptions, and then you can apply those attributes on specific methods, all methods in a class, or all methods in an assembly.