Question

I wonder what is the best way to catch an OptimisticLockException in JavaEE 6. I have the following EJB:

@Stateless
public class SeminarBooking {

public void bookSeminar(Long seminarId, int numberOfPersons) {
    ...
    //check capacity & do booking
    //OptimisticLockException can occur in this method
}

And this is my REST interface:

@Path("/seminars")
@Produces("application/xml")
@Stateless
public class SeminarResource {

    @GET
    @Path("{id}/book")
    public Seminar bookSeminar(@PathParam("id") Long id, @QueryParam("persons") Integer persons) {
        try {
            seminarBooking.bookSeminar(id, persons);
            return seminarBooking.getSeminar(id);
        }
        catch(Exception e) {
            //why is this never called?
            logger.error(This will never happen, e);
            throw new WebApplicationException(e);
        }
}

In the REST interface I catch all Exceptions, furthermore I see the OptimisticLockException if I call the interface from the browser, so why is the catch-Block never executed?

Was it helpful?

Solution

The obvious answer is that the exception in question isn't raised within that try block. Try reading the stack trace to see where it's thrown from. Given that it's related to persistence, it's likely thrown at your transaction boundary rather than from where you think it is.

OTHER TIPS

It's probably never called because the SeminarResource is a transactional EJB. That means that the transaction is committed after its bookSeminar() method has returned, and not before it has returned.

This bean should probably not be transactional. If it weren't, the transaction would start when the SeminarBooking service is called, and commit when it returns. And you would be able to catch the exception that the commit throws.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top