Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize Try/Catch code template based on exception

Does anyone know if there is a way to generate different code in the catch block automatically depending on the exception?

The Eclipse function 'Surround with try/catch' generates a try/catch block which just includes dumping a stack trace.

I'm doing a bunch of similar things in the code and so most of my exceptions will boil down to probably three or so different types. I'd like to have different catch block code for each one and have eclipse auto format based on the exception.

For example: if my code generates a RemoteConnectionException I'd like to display a dialog to the user to reconnect. If it generates a RemoteContentException I'd like to log it.

(I made these up.)

Thanks in advance

UPDATE: I've been poking around and have two potential solutions.

1) I've found something called the fast code plugin which might do what I'm looking for. http://fast-code.sourceforge.net/index.htm

2) For specifically handling exceptions I'll probably just write a generic exception handler and modify the catch block code to pass the exception to that instead of printing the stack trace. Then the java code will determine which action to take based on exception type.

like image 942
TheSporkboy Avatar asked Oct 08 '22 08:10

TheSporkboy


1 Answers

Templating has it's limits. However your problem can be solved very elegantly with Aspect. ( http://www.eclipse.org/aspectj/ ) Just create a new annotation for every type of "template-case" you need and use an around advice.

Ps: don't use printStackTrace() to syserr/sysout. There are so many production grade, lightweight logging frameworks.... pleeeaseee... don't abuse poor little System.out/err :)

EDIT:

Some example for a logging / benchmarking advice. (note: I'm using spring AOP for aspects, and lombok for easy access to the logging framework. The getCurrentUser() code is not really relevant here, it's just for getting the current user from Spring Security)

package com.XXXXXXXX.aspects;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class LoggerAspect {

    private final static String DOMAIN = "XXXXXXXX";

    private static String getCurrentUser() {
        String username = "Unknown";
        try {
            Object principal = SecurityContextHolder.getContext().
                    getAuthentication().
                    getPrincipal();
            if (principal instanceof UserDetails) {
                username = ((UserDetails) principal).getUsername();
            } else {
                username = principal.toString();
            }
        } catch (Exception e) {
        }
        return username;
    }

    @Pointcut("within(com.XXXXXXXX.services..*)")
    public void inServiceLayer() {
    }

    @Pointcut("execution(* getMatcherInfo(..)) || execution(* resetCounter(..))")
    public void notToAdvise() {
    }

    @Around("com.XXXXXXXX.aspects.LoggerAspect.inServiceLayer() && !com.XXXXXXXX.aspects.LoggerAspect.notToAdvise()")
    public Object doLogging(ProceedingJoinPoint pjp)
            throws Throwable {
        long start = System.nanoTime();
        StringBuilder sb = new StringBuilder(DOMAIN);
        sb.append('/').
                append(getCurrentUser()).
                append(" accessing ").
                append(pjp.getSignature().
                getDeclaringTypeName()).
                append('.').
                append(pjp.getSignature().
                getName());
        log.trace("START: " + sb.toString());
        Object retVal = pjp.proceed(pjp.getArgs());
        long duration = System.nanoTime() - start;
        log.trace("STOP: " + duration / 1000000 + " msec. " + sb.toString());
        return retVal;
    }
}
like image 149
Gergely Szilagyi Avatar answered Oct 13 '22 10:10

Gergely Szilagyi