I was already looking for the answer to this question, and I found the following suggestions:
- If you always expect to find a value, then throw an exception if it is missing. An exception will indicate that a problem has occurred. If the value may be absent or present, and both are valid for application logic, then return zero.
- Throw an exception only if it is really a mistake. If the behavior of the object is not expected to exist, return zero.
But how should I interpret them in my (so random) case: My web application controller receives a request to display details for a user with a specific identifier. The controller requests a level of service to get the user, and then the service returns an object if it is found. If not, a redirect to the "default location" is issued.
What if someone passes an invalid user id inside the url? Should I consider it to be "expected behavior" and return null to the controller, or perhaps I should call it "problem or unexpected behavior" and thus throw an exception inside the service method and catch it inside the controller?
Technically, this is not a big difference, but I would like to do it right by following the standard tips. Thanks in advance for any suggestions.
EDIT: I assume that the URLs generated by the application are valid and existing - when clicked by the user, the user should find the certaing identifier. I want to know how to handle a situation where a user tries to access a URL with an invalid (non-existent) user ID by manually entering the URL into the address bar of the browser.
source share