xufenglei
2017-12-04 b28a5002a58d8d0b37082da12e5b218f0951de47
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
package com.moral.common.aop;
 
import java.util.HashMap;
import java.util.Map;
 
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
 
import com.moral.common.exception.BusinessException;
 
import lombok.extern.log4j.Log4j;
 
@Log4j
@Aspect
@Component
public class ControllerAOP {
    
    @Around("execution(* com.moral.controller.*Controller.*(..))")
    public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
        long startTime = System.currentTimeMillis();
        Map<String, Object> result;
        try {
            result = (Map<String, Object>) pjp.proceed();
            log.info(pjp.getSignature() + "use time:" + (System.currentTimeMillis() - startTime));
        } catch (Throwable e) {
            result = handlerException(pjp, e);
        }
 
        return result;
    }
 
    private Map<String, Object> handlerException(ProceedingJoinPoint pjp, Throwable e) {
        Map<String, Object> result = new HashMap<String, Object>();
 
        // 已知异常
        if (e instanceof BusinessException) {
            result.put("msg", e.getLocalizedMessage());
        } else {
            log.error(pjp.getSignature() + " error ", e);
            result.put("msg", e.toString());
            //TODO 未知的异常,应该格外注意,可以发送邮件通知等
        }
 
        return result;
    }
}