In my service layer I have a method to login a user into the system. This method receives 3 arguments: String username
, String password
, int roleId
.
I need to perform couples of check in my service layer:
username
parameter. password
parameter. roleId
parameter. roleId
parameter. If any of these checks fail then the service layer should tell the controller that the login has failed and why it has failed.
If all of these checks pass then the service layer should tell the controller that the login has passed.
My concern is in case of a check fail, how can I communicate it from the service layer to the controller. Should I throw an exception? Or should I send an error code?
I think I have these options:
Throw an exception whenever a check fail. So my service method could be:
public void login(String username, String password, int roleId) throws UserServiceException;
And this could be the logic:
boolean check1Flag = isUserExist(username);
if (!check1Flag) {
throw new UserServiceException("No user exist with username '" + username + "'");
}
...
Send an error code whenever a check fail. If all of these checks pass then send 0 as code. So my service method could be:
public int login(String username, String password, int roleId) throws UserServiceException;
And this could be the logic:
boolean check1Flag = isUserExist(username);
if (!check1Flag) {
return -1; // -1 means No user exist with username paramter
}
...
Send false
whenever a check fail. If all of these checks pass then send true
. So my service method could be:
public boolean login(String username, String password, int roleId) throws UserServiceException;
And this could be the logic:
boolean check1Flag = isUserExist(username);
if (!check1Flag) {
return false;
}
...
Option 3 looks clean but I dont know how to inform controller which error occurred in this case.
Are there any other options? Are there any generally accepted design guidelines for this scenario?
Thanks
This is an opinion-based question, but you can borrow a leaf from the servlet specification, where the HttpServletRequest#login
method throws a ServletException
in the event of a failure. The reasons are obvious:
An error-handling paradigm that fits into the general exception handling mechanism of JavaEE in general. You can handle your exceptions using stock JavaEE constructs like <error-page>
and global execption handling mechanisms you'll find in things like CDI and JSF
A compact communication package. Your exception can unequivocally communicate that