Reputation: 3698
I am doing a project on C#. It's a project to send message using GSM Modem. In my project, I have several function that may give errors. I have used a string variable to store error message. The basic flow is like this.
class SMS{
string message;
public string getport(){
if(ErrorCondition)
message="Error Finding port";
return port;
}
public void executecommand(command){
if(ErrorCondition1)
message="Error Executing Command";
else(ErrorCondition2)
message="No Response from device";
}
public void sendMessage(int number, string text, out string error){
findport();
executecommand(command);
error = message;
}
}
NB:This is not the working code
This is the way I have thought to collect error message, but I not sure if I am doing it the right way. I need your help on this. Is there a better approach? Error string does not save any string. Update: As the answers of Exception are coming, I am confused about arrangement of try catch, here I have my actual code so that I'll help to give further suggestions.
public string ReadResponse(SerialPort port, int timeout)
{
string buffer = string.Empty;
try
{
do
{
if (receiveNow.WaitOne(timeout, false))
{
string t = port.ReadExisting();
buffer += t;
}
else
{
if (buffer.Length > 0)
message = "Response incomplete";
else
message = "Error on Modem";
}
}
while (!buffer.EndsWith("\r\nOK\r\n") && !buffer.EndsWith("\r\n> ") && !buffer.EndsWith("\r\nERROR\r\n"));
}
catch (Exception ex)
{
throw ex;
}
return buffer;
}
Upvotes: 0
Views: 167
Reputation: 15425
Your (pseudo) code can be refactored to use the de facto way of managing errors in C#, which are exceptions. Based on your code right there, you're used to using a special variable or return value as an error message and there's nothing wrong with that, it just won't be what other C# developers would expect.
Here's some (pseudo) code that demonstrates what I'm typing about.
class SMS {
public string GetPort() {
if (ErrorCondition) {
throw new PortNotFoundException("Error finding port.");
}
return port;
}
public void ExecuteCommand(Command command) {
if(ErrorCondition1) {
throw new UnknownErrorException("Error Executing Command");
}
else(ErrorCondition2) {
throw new NoResponseException("No Response from device");
}
}
public void SendMessage(int number, string text) {
FindPort();
ExecuteCommand(command);
}
}
You'll note that there's no out
variable in SendMessage
to handle passing out the error to calling code. That's handled by the thrown exceptions. The calling code is at liberty to determine how best to handle the exception.
Upvotes: 3
Reputation: 1166
You can declare
string message;
to
private List<string> message;
and add message to list, will help to catch multiple errors as well. Also make it private so that other class cant access the same.
Upvotes: 1