简体   繁体   中英

JavaEE Globally Catch Runtime exception

I want to "globally" catch a Runtime exception, now this sounds silly right but let me explain. I have created a interceptor that I use on all my ejbs which require authorization to use, this interceptor is called every time a method is called.

See here the code:

@Secure
@Interceptor
public class SecurityInterceptor {

    @EJB
    private SessionManager sessionManager;

    @AroundInvoke
    private Object securityCheck(InvocationContext ctx) throws Exception {
        System.out.println("hello");
        List<UserGroup> allowedRoles = (List<UserGroup>) ctx.getContextData().get("rolesAllowed");
        sessionManager.isAuthorized(allowedRoles);
        return ctx.proceed();
    }
}

Now I don't want in my Named Bean to surround the body of every method that uses one of these secured beans with a try and catch block, like this:

public List<Contracts> getContracts() {
    List<Contracts> contracts = new ArrayList<>();
    try {
        contracts = contractEntityManager.getAll();
    } catch (EJBTransactionRolledbackException e) {
        Throwable throwable = ExceptionUtils.getRootCause(e);
        if (throwable instanceof NotAuthenticatedException) {
            System.out.println("Not Authenticated");
        }
        else if (throwable instanceof UnAuthorizedException) {
            System.out.println("Not Authorized");
        }
    }
    return contracts;
}

So is there some way to globally catch a runtime exception and the redirect the user to the login page if he is unauthenticated and to a error page when he is unauthorized.

Maybe my design is just generally bad and I would need to complety rethink this idea. Please let me know.

Thank you

So, in the end, it is the in the web tier that you want to catch the exceptions. This is easy:

  • If you are only on servlets, specify the error-page element in web.xml for each exception you wish to handle, eg as follows:

     <error-page> <exception-type>fully.quallified.NotAuthenticatedException</exception-type> <location>/where/to/redirect/eg/login</location> </error-page>

    You declare the exception you want to handle globally and the URL you want to handle it, it may be a servlet, a JSP or any other resource.

  • JAX-RS offers a similar mechanism with the javax.ws.rs.ext.ExceptionMapper :

     @Provider public class NotAuthenticatedExceptionMapper implements ExceptionMapper<NotAuthenticatedException> { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM