How can I return control to the client app and ask for input again from my API?
Writing a pure API seems to be bring up some challenges. For example, I am used to writing winforms/asp.net apps where if the input I have is invalid, I can programatically bring up a dialog box/webpage.
However, an API has no开发者_高级运维 knowledge of the GUI app it may be executed from. If I have a method called TakeString (String s), and the string (s) cannot be more than 5 letters, how would I return control to the client if it was so? An exception seems like overkill? A simple return won't work if I am returning something in the method.
Thanks
An exception is exactly the right thing to do. You document that you'll only accept a string as input if it's 5 letters or fewer, and throw ArgumentException
otherwise. Why would that be overkill?
In this case, you don't even need to worry about alternative mechanisms if the client can't detect the validity of what they're passing you: if the calling code has any doubt about the arguments they're going to pass you, it's not exactly beyond the wit of man for them to check it themselves.
Trying to make the API forgiving of invalid input is a recipe for disaster. Validate the input as stringently as you can, within reason. If you force the client to behave well, you'll have a lot fewer problems later on.
An Exception is the best way to handle this.
By definition, if the user is supplying invalid data, this is an exception. The client app needs to be responsible for handling the exception and prompting the user to re-enter as necessary.
Your API (as you already pointed out) should be ignorant of the client app, including what type of app it is, so all your API has to do is say "Hey, that's invalid!" and let the developer of the client app figure out how to handle it.
For a simple example if you try the following line of C# code:
int myInt = Convert.ToInt32("SSDS");
the .NET Framework doesn't try to re-prompt the user. It just throws an exception.
精彩评论