Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practices for handling Error Strings

In my vb.net application if I have a known set of Error Strings i.e.

  • Failed because I don't know about it
  • Failed because I know about it but I can't find it
  • Failed for another reason
  • etc

And I get a response which I want to ensure doesn't have the error string in it

If returnedString.equals("Failed because I don't know about it") then 
    'do something'
End if

How would people best suggest I get away from hardcoding the error string.

Ideally a enumeration could have been be used here but wouldn't work in comparing the returned error string. (please correct me if I am wrong on this!)

Are these best held as strings in the resource file or is best to have an ErrorClass with shared public propertys for each error string and check

If returnedErrorString.equals(ErrorClass.UnknownString) then 
        'do something'
End if

Or is there any other (better?) way to do this?

EDIT: The Exception suggestions I think would not be best in this situation as the returned error code doesn't necessarily cause the application to fail but will perhaps alter program flow as in what to display to the user and I have to look at the error strings as these are out with my control and returned from an external application

like image 454
Dean Avatar asked Dec 20 '25 00:12

Dean


2 Answers

I would say that the preferred way would be not to use error strings, but rather to create custom Exception classes for the different, um, exceptions:

UnknownException
NotFoundException
OtherReasonException

Then you have a type-safe way of determining the error cause, that is also disconnected from problems with translated text and similar.

MSDN has an article on how to create user-defined exceptions.

like image 157
Fredrik Mörk Avatar answered Dec 21 '25 19:12

Fredrik Mörk


In my 30+ years of experience, it has always been a mistake to look at error strings to determine programatically what went wrong. What if the punctuation changes?

I agree with the suggestion to use custom exceptions, but I would only create a single custom exception. I would define an enum for the reason:

public enum ExceptionReason {
    Unknown,
    NotFound
}

I would give your custom exception a property of this enum type.

For the case of "something else", just throw the existing Exception class. In fact, you'll like find out about "something else" through an exception, in which case, don't catch it - just let it pass up.

like image 20
John Saunders Avatar answered Dec 21 '25 19:12

John Saunders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!