Handling Errors From HTTPWebRequest/HTTPWebResponse - oop

I have a class called Hotmail that contains various method such as login, logout etc.
To illustrate the confusion I'm having I have a login method that logs the user into Hotmail via my software. The login method returns a HttpWebResponse object. But, within the login method any number of things could happen such as wrong credentials being entered or a timeout.
I'm in some confusion about how, and where to handle such errors.
In the case of the wrong credentials being entered, or a timeout, it would be pointless, or sometimes not possible to return a HttpWebResponse object. What would be the best way to handle such errors?
Should I create custom Exceptions so the code that's calling the method can check for such errors and handle them?
What's the conventional way to handle these sorts of errors as I'm sure this is a common point of confusion?

Assuming that you have something like Hotmail>>login(user, password) I would definitely use exceptions. How fine grained to be with exceptions its up to you (and your domain model) and it can be hard to achieve a balance.
For this case I would definitely have exceptions for the most important events (like WrongCredentialsException) but I wouldn't have an exception class for every 4XX and 5XX response errors. However, according to your domain and personal tastes you could have a ClientException and ServerException, with an instance variable stating the error number instead of just having a ConnectionException.
HTH

Related

Exceptions and StatusCode in ASP.NET Core MVC

We have UseExceptionHandler (handle Exeptions) and UseStatusCodePages (handle StatusCode). Why in ASP.NET Core MVC we using StatusCodeResult than just handy extend Exception?
UseExceptionHandler is generally used to catch up unexpected errors and preset them in a more friendly manner to the user.
Whereas status codes are more important in REST API to signal the client the success or failure (and specific cause of the failure) of the specific operation.
Controller action should never throw exception and access a specific resource (i.e. db record) which doesn't exist you should return 404 (not found). When passed data is invalid rest apis return "400 bad request", on success 200. When new resource is created 201 (with "Location" header which contains the url to the new resource, see CreatedAtAction method of the controller class).
With views it works differently where you render the error directly into the HTML Code. You can also return status codes with MVC-esque view controllers and handle it with UseStatusCodePages (i.e. showing a generic NotFound.cshtml template for resources which don't exist).
Also your question sounds like you want to use exceptions to set status code, this is wrong for a couple of reasons.
Exceptions should be (as their name suggest) exceptional; Read: when something unexpected happens. For example if you try to withdraw a negative balance from your bank account and further processing it makes no sense or becomes impossible.
When you expect an error, you should return a result or handle it differently. For validations you should use Result classes (i.e. IdentityResult from ASP.NET Core Identity, which contains a Success property and a property which contains a list of error messages in case the operation or the validation fails).
Throwing and catching Exceptions is quite expensive, so they should really only be thrown when (as pointed above) something unexpected happens. Not finding a record is nothing unexpected.
(Ab)using exceptions for flow control (deciding which code path to execute) is just wrong. That's what if/switch and patterns like strategy pattern are for. Exceptions will just make the code unreadable and harder to maintain.

Best practice: throwing Exception or using Validator on User Input

Recently I've been into multiple arguments on whether to throw an exception on false User Input.
Example: I'm trying to login though my account is not activated. As the programmer in an OO-language, I could handle this in a few ways. For this case, lets stick to these two:
Throw a custom Exception from the local Service with a representative way, extending Exception. Catching this in the class handling User Input.
Use a Validator to call the local Service to check whether this account is logged in.
My vision, like many others, an Exception represents a fault in the program. E.g. database unreachable, error in parsing data.
Vision of many others as well, the case of logging in without being activated is not a succesful scenario on any use case and will thus fail. This shouldn't not happen and is worth throwing an Exception for.
Personally, I would handle this kind of problem with a Validator, sticking to Exceptions for just the faults in the program. However though, I would like to get a constructive answer on which case is preferred. If possible, referring to any documentation. I'm using Java, though this problem is not restricted to any language (as long as it's OO I guess).
In case of a validation error, the flow of your application must be interrupted. For example, you must terminate a singing up progress if an invalid mail address supplied. Thus, the exceptions can be used for the purpose of user input validation.
As an example use, you can check JSF. It benefits from exception mechanism of Java to handle user input validations. The following links can be useful:
http://www.mkyong.com/jsf2/custom-validator-in-jsf-2-0/
http://www.ibm.com/developerworks/library/j-jsf3/

RestKit how to check for wrong username or password error

I want to be able to notify the user if he entered the wrong username/password, or if for example the database is down. I am not sure if I need to do it in the didLoadResponse and just check that the response is not isOK or in the didFailLoadWithError.
Thanks
How you handle it depends on how you perform a login.
If you do basic authentication, by passing the username and password in the header of the request, then you'll get an error back from the service you're calling. And your delegate method, "objectLoader:didFailWithError:" method will get called. This method will most likely get called if there's a catastrophic problem on the backend, like the database being down.
If you have a separate webservice that performs a login operation, then it probably sends back a valid block, indicating whether the user-pass was valid or not. In this case, your "objectLoader:didLoadObject:" method probably got called, and you'll have to decipher the result appropriately.
Keep in mind that this behavior is totally controlled by what the back-end services do. If you can't talk directly with the people working on the services, then this may just be trial-and-error, and until you discover how those services work.

Best way to return various results from login wcf service

string Authenticate(string username, string password);
Give a simple authenticate method that takes in a username and password and returns a token if successful, I need to be able cope cope with various failure situations including - invalid credentials, locked account, awaiting verification etc.
What is the best way to go about this?
I was thinking about either of the two options below but am open to anything else:
(1) changing response to an object with an enum as well as the token. A bit worried with regard to versioning with this method though.
(2) faultcontracts for each of the failure cases. Not sure about performance here though.
You should use the FaultContract only when you want return more details/manage an exception on the client side. An exception (as you guess by the name itself) is something you couldn't foresee or rather something that happen against your will :-)
In your case you already know the login can be locked, invalid etc. I think you should return an enumerator (or encapsulate it into an object) to provide more information about instead of raise an exception to force to use fault contract
I hope it makes sense

Simultaneous LINQ data retrieval problem

I came across a very strange problem which never happened to me before.
In the login code:
var sqlLogin = db.LoginRetrieve(loginID, archived).SingleOrDefault();
//(db is the linq data context)
--problem:
If two users login at the same time, this line of code will throw an exception which is "The required column 'UserLoginID' does not exist in the results."
But if a single user logs in or two users don't click the button at the same time, it will have no exception.
Is there anyone can share some lights on this? Thanks in advance.
Han
I suspect that your DataContext is shared between requests.
Don't do that.
You should create a separate DataContext for each request.
Otherwise, you'll get nasty threading issues like this one. (DataContext isn't thread-safe)
In general, you should be very careful when sharing objects between requests (eg, statics or Application / Session state).
Unless you know specifically otherwise, you should assume that the object is not thread-safe and cannot be shared.