简体   繁体   English

从消费类获取警告

[英]Fetch warning from consuming class

Let's say I have a service class that does something for me and a consumer class that consumes this service. 假设我有一个为我做某事的服务类和一个消费此服务的消费者类。 The service relies on throwing exceptions to the consumer when it feeds it something that won't work. 该服务依赖于在向用户提供无法正常工作的东西时向其抛出异常。

All is good, I can easily catch these exceptions from the consuming side and do something useful with them. 一切都很好,我可以从使用方轻松捕获这些异常,并对它们做一些有用的事情。 Like displaying a message to the user. 像向用户显示消息。

However, what if the service run into something that's not good, but not really an error. 但是,如果服务运行不正常但不是真正的错误,该怎么办? It may be some information to the user saying "Don't do it this way, it'll work but you've probably made a mistake". 用户可能会收到一些信息,说“不要这样,它会起作用,但您可能犯了一个错误”。 A warning that is. 是一个警告。

How would you go about notifying the consumer class of this warning so it can be for example shown to the user? 您将如何通知消费者类别此警告,以便例如向用户显示警告? Is the only way to pass some sort of warning service (much like a logger) to the service and then check that for any warnings after the service is done? 将某种警告服务(很像记录器)传递给服务,然后在服务完成后检查是否有任何警告的唯一方法?

I should also say that the service is within my domain so I can do pretty much what I want with it. 我还应该说该服务在我的域之内,因此我可以做很多我想做的事情。

Have you thought about your consumer class throwing events and have your service class subscribe to them? 您是否考虑过您的消费者类抛出事件并让服务类订阅它们? See here 看这里

I would think about wrapping the entire service call into a context, something like this: 我会考虑将整个服务调用包装到上下文中,如下所示:

class CallContext<TInput, TOutput>
{
    TInput InputValue { get; set; }

    TOutput OutputValue { get; set; }

    ICollection<String> Warnings { get; set; }
}

class MyService
{
    void SomeOperation(CallContext<int, int> context)
    {
        context.OutputValue = context.InputValue * 2;

        if (context.IntputValue < 0)
            context.Warnings.Add("Input value less than zero may have undesired results.");
    }
}

The service is quite happy to continue with the operation despite the fact that it has recognised something peculiar with the input. 该服务很高兴继续操作,尽管事实是它已经识别出输入所特有的东西。 It doesn't stop the function running, but the service is able to warn the caller that the result may be unexpected. 它不会停止函数的运行,但是该服务能够警告调用者结果可能是意外的。

class Consumer
{
    void CallService()
    {
        var context = new Context<int, int>()
        {
            InputValue = -1;
        }

        myService.SomeOperation(context);

        Console.WriteLine(context.OutputValue);

        foreach(string warning in context.Warnings)
            Console.Writeline(warning);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM