alb3rtuk

Java code posted by alb3rtuk
created at 17 Jun 17:47

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package gov.hi.dhs.fmm.lib.db;

import gov.hi.dhs.fmm.lib.exceptions.ClientErrorException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.dao.DataIntegrityViolationException;

/**
 * Due to the nature of the @Around annotation, there can only be one concrete extension of this
 * class at anytime
 */
@Aspect
public abstract class AbstractPersistenceExceptionInterceptor {

    /**
     * Wraps method to catch database persistence related errors and handle them
     *
     * @param pjp {@link ProceedingJoinPoint}
     * @param interceptPersistenceException {@link InterceptPersistenceException}, contains entity
     *     specific translator class
     * @return join point proceed
     * @throws Throwable for exception
     */
    @Around(value = "@annotation(interceptPersistenceException)")
    public Object handlePersistenceException(
            ProceedingJoinPoint pjp, InterceptPersistenceException interceptPersistenceException)
            throws Throwable {
        try {
            return pjp.proceed();
        } catch (DataIntegrityViolationException e) {
            throw handleDataIntegrityViolationException(
                    interceptPersistenceException.translator(),
                    e.getMostSpecificCause().getMessage());
        }
    }

    /**
     * Wraps method to catch database persistence related errors and handle them
     *
     * @param translatorClass ConstraintTranslator class which will be instantiated in this method.
     *     NOTE: Due to coming from annotation, the amount of generic typing that we can perform is
     *     limited.
     * @param errorMessage message taken from root cause of {@link DataIntegrityViolationException}
     * @return ClientErrorException with user friendly message
     * @throws IllegalAccessException for instancing translator class
     * @throws InstantiationException for instancing translator class
     */
    protected abstract ClientErrorException handleDataIntegrityViolationException(
            Class<? extends ConstraintTranslator<?>> translatorClass, String errorMessage)
            throws IllegalAccessException, InstantiationException;
}
2.25 KB in 2 ms with coderay