S7NetPlus / s7netplus

S7.NET+ -- A .NET library to connect to Siemens Step7 devices
MIT License
1.3k stars 581 forks source link

How to handle error with PlcExeption? #385

Closed TienLam1993 closed 3 years ago

TienLam1993 commented 3 years ago

Anyone can give me instructions on how to use PlcExeption to handle errors effectively? How I can improve this code to know exactly what kind of problem I am facing? For example, I want to know whether the CPU type is wrong or the Ip address is wrong. Just like in the older versions where I can check in the Open().ErrorCode

         try
        {
        plc = new Plc(cpu, textboxIp.Text, Convert.ToInt16(textboxRack.Text), Convert.ToInt16(textboxSlot.Text));

        plc.Open(); 
        }

        catch (Exception e)

        {
            MessageBox.Show(e.Message);
            textBox1.Text = "Error";
        }

Thanks!

mycroes commented 3 years ago

Hi @TienLam1993,

A couple of things have changed in the library. For one, all ErrorCode returns have been replaced with exceptions, because that's the common approach for error handling in C#. However, you already noticed that and you're mentioning two separate situations:

  1. Incorrect CPU type
  2. Invalid IP address

I had to look up the old code to see how this was handled, and my conclusions are as follows:

  1. There's no error about incorrect CPU types, just a meaningless ConnectionError hiding the original exception.
  2. The detection of an invalid IP address is based on a socket timeout. A timeout doesn't mean the IP address is invalid, my opinion (both personal and professionally) is not to assume based on incomplete information.

This by itself doesn't help you much, but I hope it explains the extent of the original error codes and the margin for error that was there. You can now catch the actual exceptions that caused the method not to succeed. I can imagine a desire to get a bit more information from the methods, as you can't easily detect whether at least the TCP connection succeeded. On the other hand the CpuType passed into S7NetPlus does nothing more than setting some identifiers, which if I'm not mistaken are actually equal for at least 3 of the supported CpuTypes.

Anyway, closing this issue, feel free to reopen if you have more questions.