在C#中处理异常的Modbus 2.0

问题描述 投票:0回答:1

我正在努力 web-api 其中,我a使用的是 Modbus 协议库由 sontx. 在文档中,它被提及。

异常处理

有几种情况下,响应被破坏,没有任何响应(可能是slave宕机了),......。在这些情况下,将抛出一个异常,即 "异常"。try-catch 语句来处理这些情况。

异常有三种:- EmptyResponsedException: 从机没有任何响应,那好像是从机宕机了,连接中断了...... - MissingDataException: 响应字节数小于所需字节数,例如:所需字节数的长度为11,但接收到的字节数的长度为9。DataCorruptedException: 校验失败,响应从属ID错误,响应函数代码错误......。

try {
var responseBytes = stream.RequestFunc3(0x11, 0x006B, 0x0003);
// handle your response bytes
}
catch(Exception e) {
if (e is DataCorruptedException) {
    BroadcastHandledExceptionEvent("checksum is failed", e);
}
else if (e is EmptyResponsedException) {
    BroadcastHandledExceptionEvent("request timeout", e);
}
else if (e is MissingDataException) {
    BroadcastHandledExceptionEvent("Missing response bytes", e);
}
else {
    throw e;
}
}

当我试图将这段代码添加到我的代码中时,我得到了如下的错误信息。

在当前上下文中不存在'BroadcastHandledExceptionEvent'这个名字。

enter image description here

我试图找到它的解决方案,但我什么都没有得到。

任何帮助将是非常感激的。

c# exception asp.net-web-api2 modbus
1个回答
1
投票

看起来像 BroadcastHandledExceptionEvent 只是例子中的一个仲裁方法。你必须根据异常类型实现自己的错误处理。


0
投票

"BroadcastHandledExceptionEvent "只是一个示例方法的名称,文档中用它来演示你如何处理捕获异常类型。你可以用你自己的方法来替换它,将异常消息输出到UI,写到日志等。

例如,使用它们相同的方法名(如果有必要,还可以使用 "广播 "异常的功能)。

class ModbusTest
{
    public event EventHandler<string> ModbusExceptionThrown;

    public void TestRead()
    {
        try
        {
            var responseBytes = stream.RequestFunc3(0x11, 0x006B, 0x0003);
            // handle your response bytes
        }
        catch (Exception e)
        {
            if (e is DataCorruptedException)
            {
                BroadcastHandledExceptionEvent("checksum is failed", e);
            }
            else if (e is EmptyResponsedException)
            {
                BroadcastHandledExceptionEvent("request timeout", e);
            }
            else if (e is MissingDataException)
            {
                BroadcastHandledExceptionEvent("Missing response bytes", e);
            }
            else
            {
                throw e;
            }
        }
    }

    // logs exception stacktrace to console and raises event with message string
    protected virtual void BroadcastHandledExceptionEvent(string Message, Exception Ex)
    {
        Console.WriteLine(Ex.StackTrace);
        EventHandler<string> handler = ModbusExceptionThrown;
        handler?.Invoke(this, Message);
    }
}

现在你的父对象可以监听modbus异常消息 如果不需要的话,你可以简单地将其记录到控制台,文件,或者其他什么地方。

© www.soinside.com 2019 - 2024. All rights reserved.