package com.macro.mall.component;

import com.macro.mall.dto.CommonResult;
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.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

/**
 * HibernateValidator错误结果处理切面
 */
@Aspect
@Component
@Order(2)
public class BindingResultAspect {
    @Pointcut("execution(public * com.macro.mall.controller.*.*(..))")
    /*SpringMVC的参数验证*/
    /*Spring验证的错误返回BindingResult*/
    public void BindingResult() {
    }

    @Around("BindingResult()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    	/*Around(value="BindingResult()"*/
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof BindingResult) {
            	/*参数正常，验证通过*/
                BindingResult result = (BindingResult) arg;
                if (result.hasErrors()) {
                	/*传递参数有误*/
                    return new CommonResult().validateFailed(result);
                    /* 验证不通过，产生异常*/
                    /*返回错误文件，错误信息*/
                }
            }
        }
        return joinPoint.proceed();//调用AOP中环绕通知中proceed方法
    }
}
