I have a service that saves a tree-like structure to a database. Before persisting the tree, the tree gets validated, and during validation, a number of things can go wrong. The tree can have duplicate nodes, or a node can be missing an important field (such as its abbreviation, full name, or level).
In order to communicate to the service what went wrong, I'm using exceptions. When the validateTree() method encounters a problem, it throws the appropriate exception. The HttpService class then uses this exception to form the appropriate response (e.g. in response to an AJAX call).
public class HttpService {
private Service service;
private Logger logger;
// ...
public HttpServiceResponse saveTree(Node root) {
try {
service.saveTree(root);
} catch (DuplicateNodeException e) {
return HttpServiceResponse.failure(DUPLICATE_NODE);
} catch (MissingAbbreviationException e) {
return HttpServiceResponse.failure(MISSING_ABBREV);
} catch (MissingNameException e) {
return HttpServiceResponse.failure(MISSING_NAME);
} catch (MissingLevelException e) {
return HttpServiceResponse.failure(MISSING_LEVEL);
} catch (Exception e) {
logger.log(e.getMessage(), e. Logger.ERROR);
return HttpServiceResponse.failure(INTERNAL_SERVER_ERROR);
}
}
}
public class Service {
private TreeDao dao;
public void saveTree(Node root)
throws DuplicateNodeException, MissingAbbreviationException, MissingNameException, MissingLevelException {
validateTree(root);
dao.saveTree(root);
}
private void validateTree(Node root)
throws DuplicateNodeException, MissingAbbreviationException, MissingNameException, MissingLevelException {
// validate and throw checked exceptions if needed
}
}
I want to know, is this a good use of exceptions? Essentially, I'm using them to convey error messages. An alternative would be for my saveTree() method to return an integer, and that integer would convey the error. But in order to do this, I would have to document what each return value means. That seems to be more in the style of C/C++ than Java. Is my current use of exceptions a good practice in Java? If not, what's the best alternative?
No, exceptions aren't a good fit for the validation you need to do here. You will likely want to display multiple validation error messages, so that the user can see all the validation errors at once, and throwing a separate exception for each invalid input won't allow that.
Instead create a list and put errors in it. Then you can show the user the list of all the validation errors.
Waiting until your request has gotten all the way to the DAO seems like the wrong time to do this validation. A server-side front controller should be doing validation on these items before they get passed along any farther, as protection against attacks such as injection or cross-site scripting.
TL;DR The Java-side parts you showed us are nearly perfect. But you could add an independent validation check and use that from the client side before trying to save.
There are many software layers involved, so let's have a look at each of them - there's no "one size fits all" answer here.
For the Service object, it's the perfect solution to have it throw exceptions from the saveTree() method if it wasn't able to save the tree (for whatever reason, not limited to validation). That's what exceptions are meant for: to communicate that some method couldn't do its job. And the Service object shouldn't rely on some external validation, but make sure itself that only valid data are saved.
The HttpService.saveTree() should also communicate to its caller if it couldn't save the tree (typically indicated by an exception from the Service). But as it's an HTTP service, it can't throw exceptions, but has to return a result code plus a text message, just the way you do it. This can never contain the full information from the Java exception, so it's a good decision that you log any unclear errors here (but you should make sure that the stack trace gets logged too!), before you pass an error result to the HTTP client.
The web client UI software should of course present detailed error lists to the user and not just a translated single exception. So, I'd create an HttpService.validateTree(...) method that returns a list of validation errors and call that from the client before trying to save. This gives you the additional possibility to check for validity independent of saving.
Why do it this way?
You never have control what happens in the client, inside some browser, you don't even know whether the request is coming from your app or from something like curl. So you can't rely on any validation that your JavaScript (?) application might implement. All of your service methods should reject invalid data, by doing the validation themselves.
Implementing the validation checks in a JavaScript client application still needs the same validation inside the Java service (see above), so you'd have to maintain two pieces of code in different languages doing exactly the same business logic - don't repeat yourself! Only if the additional roundtrip isn't tolerable, then I'd regard this an acceptable solution.
Visible and highly noticeable, both in terms of the message itself and how it indicates which dialogue element users must repair.
From Guru Nielsen,
https://www.nngroup.com/articles/error-message-guidelines/
Related
I am trying to intercept an Exception thrown by my algorithm in Java, and change the text to another language, and show it to the user. Is this possible in java?
Sorry by my English.
You can catch an exception, and then throw a new one of the same type (or a different type if you prefer). Then translate the message from the original exception and pass it into the new exception. Something like the following (not tested):
try {
// do something
}
catch (Exception e) {
throw new Exception(translate(e.getMessage()))
}
public String translate(String message) { /* translation code */ }
Update in response to comment:
If you can modify the application (and particularly if the application uses custom exceptions derived from a few base classes) then you might be able to modify these to retrieve translated messages (but if you could do that, you could build in the translated messages, or full internationalisation, from the start!).
Intercepting and replacing all Exceptions globally is probably not possible, although it looks like you can at least detect them globally using debug hooks - see this answer. It's conceivable that you could modify the Exception message on-the-fly using reflection, but this sounds pretty nasty.
One final possibility is to use Aspect-Oriented Programming (AOP) to compile-in extra behaviour around code that throws an exception (see this question, for example). You'd need to recompile the whole application using AOP tools though, and would probably still need to modify the application code a bit.
I think you want Thread.setDefaultUncaughtExceptionHandler()
This issue had more details if you need them...
swing uncaughtexceptionhandler
You would need to translate the message text of an exception only if your were reporting the message text of exceptions. But doing that is a mistake.
The message was created when the exception was thrown. It therefore at best can provide only very low level information, which can be inappropriate for reporting to a user.
Philosophically, using the message is against the whole point of exceptions, which is to separate the detection and initiation of error handling (the throw part) from completion of handling and reporting (the catch part). Using the message means the message must be good for reporting, which moves responsibility for reporting to the location that should be responsible for only detection and initiation. That is, I'd argue that the getMessage() part of the design of Throwable was a mistake.
Instead of doing that, follow the advice to choose what message to report to the user at the point where your catch the exception. You can internationalize that message use the usual Java text internationalization facilities.
I solved my question with this solution
public class ParamsException extends RuntimeException {
private static final long serialVersionUID = 7161500238672497882L;
public ParamsException() {
super();
}
public ParamsException(String message) {
super(new BaseResourcesBusiness().getException(message));
}
public ParamsException(Throwable cause) {
super(cause);
}
public ParamsException(String message, Throwable cause) {
super(new BaseResourcesBusiness().getException(message), cause);
}
}
the BaseResourceBusiness.getException(message) get the message from a XML or Database to a specific language. So all my exception is created in this mode
public static final class NotFoundInDatabaseException extends ParamsException {
private static final long serialVersionUID = -1595240938885629473L;
public NotFoundInDatabaseException () {
super("Not found in database");
}
}
in the code im using with this mode throw new NotFoundInDatabaseException ()
I own a DDD/CQRS application.
My question concerns the handling of an item creation through POST (Rest).
CQRS (based on CQS principle) promotes that commands should never return a value.
Queries are there for that.
So I wonder how to handle the use case of Item creation.
Here's my current command handler pattern (light for the sample (no interfaces etc.)):
#Service
#Transactional
public CreateItem {
public void handle(CreateItemCommand command) {
Customer customer = customerRepository.findById(command.customerId);
ItemId generatedItemId = itemRepository.nextIdentity(); //generating the GUID
customer.createItem(generatedItemId, .....);
}
}
By reading this article, an easy method would be to declare an output property in the command, populated at the end of the handle method like this:
public void handle(CreateItemCommand command) {
Customer customer = customerRepository.findById(command.customerId);
ItemId generatedItemId = itemRepository.nextIdentity(); //generating the GUID
customer.createItem(generatedItemId, .....);
command.itemId = generatedItemId; //populating the output property
}
However, I see one drawback with this approach:
- A command, in theory, is meant to be immutable.
This itemId would then be sent thanks to the calling controller (webapp) through Location Header with the status 201 or 202 (depending if I expect async or not).
An other solution would be to let the controller initialize the GUID by accessing the repository itself, thus letting the command immutable:
//in my controller:
ItemId generatedItemId = itemRepository.nextIdentity(); //controller generating the GUID
createItem.handle(command);
// setting here the location header (201-202) containing the URL to the newly created item with the using the previous itemId.
Drawback: Controller (adapter layer) accessing directly the repository ..., that is too low-level IMO.
My extreme client being a Javascript application, I might have another solution to let the Javascript itself generate a GUID, and feed CreateItemCommand with it before sending the whole command to server.
Advantage: No more issues about potential violation of CQ(R)S guidelines.
Drawback: Should check the validity of the passed id at server side. Although there would have an index unique on this preventing an unexpected insertion in database.
What is the best (or just a good) strategy to handle this?
I am the developer of a CRM application based on the CQRS pattern. I tend to see commands as immutable. The team decided early on, that all IDs are generated on the client to have immutable commands. This is perfectly ok, as we are using UUIDs. So we are quite confident, that the IDs are valid and there are no ID collisions. We went well with that approach up to this point - I can definitely recommend this. In that scenario the client just knows the IDs.
Sometimes it happens though - especially in manual testing - that a create command is dispatched twice with the same ID. In that case the addition of events in the event store fails (we use event sourcing) with a duplicate key exception. The exception is passed to the controller. In fact we do return results from command executions with a call back, even though it's just "everything ok" most of the time - so no exception thrown. Also command validation is done this way. We do this using a command bus concept.
I would recommend taking a look at the Axon framework. We use it, it provides the common building blocks, and it just works. Maybe you can get some inspirations from that!
I would like to know what is the best way to handle validation errors in medium/big Java EE application.
Suppose I have managed bean and facade as it is below.
class SomeManagedBean {
#EJB
SomeFacade someFacade;
public void performSomeAction() {
(...)
someFacade.businessAction(loggedUser, editedEntity);
(...)
}
}
class SomeFacadeImpl {
public Object businessAction(User user, Entity entity) {
if (!isInCorrectStateToDoAction(entity)) {
// error A
}
(...)
if (!hasRightToDoAction(user, entity)) {
// error X
}
doAction(user, entity);
}
}
I expect that businessAction from SomeFacade should validate their inputs and check if it can do this business action with given arguments. It's because I may use this business method in several places in application and I do not want copy validation code.
Suppose I would like to use FacesMessage to provide to client informations about validation errors.
Some solutions:
exceptions - when something is wrong with arguments I simply throw an Exception
so I have to throw IncorrectStateForActionException, NoRightToDoActionException
why not: I can throw only one exception so I can't notify user about several things: "You don't have rights", (...), "Entity is incorrect state"
beside exception shouldn't be used to provide logic of our application
some Result class
class Result<T> {
T returnedValueFromMethod;
List<ProcessingError> errors;
}
now definition of my business method looks like:
public Result<Object> businessAction(User user, Entity entity)
when something is wrong I add error information to Result
when everything is all right I put returned value to my Result object and return this object
why not: this seems like kind of "error code" in pretty complex structure. Because of that recommendation which tells "change error codes into exception" it's understandable why we would like to avoid it.
we can do validation in facade and controller
why not: duplicated code
validation only in controller and action in facade
why not: it could be dangerous when we use this businessAction method from other place in code
we can do two methods in facade: validation and action (Query Command Separation)
result from validation should contain every possible error which may occur so it's pretty strange structure
we can do several methods for validation (errors from A to X)
it's easy to provide error messages
but this solutions seems just stupid
any other ideas?
What would be the best solution?
Do authentication/validation in business layer and let it throw an exception in case of failure. You can just handle it in JSF action method.
E.g.
#EJB
private SomeService service;
public void someAction() {
try {
service.doSomething();
addGlobalInfoFacesMessage("Doing something succeed!");
} catch (SomeBusinessException e) {
addGlobalErrorFacesMessage("Doing something failed with {0}", e.getMessage());
}
}
Or, you can let it go and have the container handle it by an <error-page> on the specific <exception-type>.
As to performing authentication and validation all by itself, the Java EE stack offers annotations like JAAS #RolesAllowed for authentication and JSR303 #NotNull, #Size, etc for model. This should reduce the if check boilerplate inside the service methods itself.
recently I found a function like this in a generic JSR245 portlet class:
public class MyGenericPortlet extends GenericPortlet {
#Override
public void processAction(ActionRequest rq, ActionResponse rs) throws PortletException{
String actParam = rq.getParameter("myAction");
if( (actParam != null) && (!("").equals(actParam))) {
try{
Method m = this.getClass().getMethod(actParam, new Class[]{ActionRequest.class, ActionResponse.class});
m.invoke(this, new Object[]{rq, rs});
}
catch(Exception e){
setRequestAttribute(rq.getPortletSession(),"error", "Error in method:"+action);
e.printStackTrace();
}
}
else setRequestAttribute(rq.getPortletSession(),"error", "Error in method:"+action);
}
}
How safe is such code? As far as I can see the following problems might occur:
A parameter transmitted from the client is used unchecked to call a function. This allows anyone who can transmit data to the corresponding portlet to call any matching function. on the other hand the function to be called must have a specific interface. Usually such functions are very rare.
A programmer might accidentaly add a function with a corresponding interface. As only public functions seem to be found this is no problem as long as the function is private or protected.
The error message can reveal information about the software to the client. This shouldn't be a problem as the software itself is Open Source.
Obviously there is some room for programming errors that can be exploited. Are there other unwanted side effects that might occur? How should I (or the developers) judge the risk that comes from this function?
If you think it is safe, I'd like to know why.
The fact that only public methods with a specific signature can be invoked remotely is good. However, it could be made more secure by, for example, requiring a special annotation on action methods. This would indicate the developer specifically intended the method to be an invokable action.
A realistic scenario where the current implementation could be dangerous is when the developer adds an action that validates that the information in the request is safe, then passes the request and response to another method for actual processing. If an attacker could learn the name of the delegate method, he could invoke it directly, bypassing the parameter safety validation.
I have a code that saves a bean, and updates another bean in a DB via Hibernate. It must be do in the same transaction, because if something wrong occurs (f.ex launches a Exception) rollback must be executed for the two operations.
public class BeanDao extends ManagedSession {
public Integer save(Bean bean) {
Session session = null;
try {
session = createNewSessionAndTransaction();
Integer idValoracio = (Integer) session.save(bean); // SAVE
doOtherAction(bean); // UPDATE
commitTransaction(session);
return idBean;
} catch (RuntimeException re) {
log.error("get failed", re);
if (session != null) {
rollbackTransaction(session);
}
throw re;
}
}
private void doOtherAction(Bean bean) {
Integer idOtherBean = bean.getIdOtherBean();
OtherBeanDao otherBeanDao = new OtherBeanDao();
OtherBean otherBean = otherBeanDao.findById(idOtherBean);
.
. (doing operations)
.
otherBeanDao.attachDirty(otherBean)
}
}
The problem is:
In case that
session.save(bean)
launches an error, then I get AssertionFailure, because the function doOtherAction (that is used in other parts of the project) uses session after a Exception is thrown.
The first thing I thought were extract the code of the function doOtherAction, but then I have the same code duplicate, and not seems the best practice to do it.
What is the best way to refactor this?
It's a common practice to manage transactions at one level above DAOs, in services or other business logic classes. That way you can, based on the business/service logic, in one case do two DAO operations in one transaction and, in another case, do them in separate transactions.
I'm a huge fan of Declarative Transaction Management. If you can spare the time to get it working (piece of cake with an Application Server such as GlassFish or JBoss, and easy with Spring). If you annotate your business method with #TransactionAttribute(REQUIRED) (it can even be set to be done as default) and it calls the two DAO methods you will get exactly what you want: everything gets committed at once or rolled back over an Exception.
This solution is about as loosely coupled as it gets.
The others are correct in that they take in to account what are common practice currently.
But that doesn't really help you with your current practice.
What you should do is create two new DAO methods. Such as CreateGlobalSession and CommitGlobalSession.
What these do is the same thing as your current create and commit routines.
The difference is that they set a "global" session variable (most likely best done with a ThreadLocal). Then you change the current routines so that they check if this global session already exists. If your create detects the global session, then simply return it. If your commit detects the global session, then it does nothing.
Now when you want to use it you do this:
try {
dao.createGlobalSession();
beanA.save();
beanb.save();
Dao.commitGlobalSession();
} finally {
dao.rollbackGlobalSession();
}
Make sure you wrap the process in a try block so that you can reset your global session if there's an error.
While the other techniques are considered best practice and ideally you could one day evolve to something like that, this will get you over the hump with little more than 3 new methods and changing two existing methods. After that the rest of your code stays the same.