spring 和 spirngMvc 中 异常处理

spring 中 的 异常处理 使用的是aspectj

@Aspect
@Component
/**
 * 
 * @author ****
 * @createData 2017年7月13日 上午8:36:23
 * @说明 :出了一些空值。。。
 */
public class AjaxEntityHandler {

    // @Pointcut("@annotation(org.zkdg.utils.annotations.AfterHandler)")

    @Pointcut("@annotation(org.zkdg.utils.spring.annotations.NotNullVariable)")
    // @Pointcut("execution(* org.dcexam.*.service.*.*(..))")
    public void beforeCall() {
        // service方法调用之前,检测参数,仅限第一个参数, 不能为空值
    }

    /**
     * service发生异常时调用
     */
    @Pointcut("execution(* org.dcexam.*.service.*.*(..))")
    public void afterThrowEx() {
        System.out.println("************











*******");
    }

    @Around(value = "beforeCall()")
    public AjaxEntity doBefore(ProceedingJoinPoint point) throws Throwable {
        // TODO Auto-generated method stub
        Object[] args = point.getArgs();
        if (args == null || args[0] == null) {
            return new AjaxEntity("warning", "未选择任何数据。。。");
        }
        if (args[0] instanceof String) {
            String str = (String) args[0];
            if (str.equalsIgnoreCase(""))
                return new AjaxEntity("warning", "未选择任何数据。。。");
        }

        AjaxEntity ajax = (AjaxEntity) point.proceed(args);

        return ajax == null ? AjaxEntity.ERROR("操作失败") : ajax;
    }

    /**
     * 
     * @param joinPoint
     *            连接点
     * @param ex
     *            异常
     * @return AjaxEntity 异常信息
     */
    @AfterThrowing(value = "afterThrowEx()", throwing = "ex")
    public void doAfterThrowEx(JoinPoint joinPoint, Exception ex) {
        AjaxEntity ajax = new AjaxEntity();

        if (ex.getCause() instanceof SQLException) {
            // 数据库操作异常
            ajax = AjaxEntity.ERROR("操作数据库时出现异常");
        }

    }

}
spring.xml 中 配置

<!-- 注解aop,支持注解 -->
<aop:aspectj-autoproxy />

事务 切点配置

<!-- 配置参与事务的类 -->
<aop:config expose-proxy="true" proxy-target-class="true">
<aop:pointcut id="txPointCut"
expression="execution(* org.dcexam.*.service.*.*(..))" />
<aop:advisor pointcut-ref="txPointCut" advice-ref="txAdvice" />
</aop:config>

注意   expose-proxy="true" proxy-target-class="true" 是 aspectj 代理  

在springMvc 中 ,由于 spring 与 springmvc 为 不同的容器。尽量不要使用aspecj代理  ,使用spring mvc 自带的 HandlerExceptionResolver 处理 异常


package org.zkdg.utils.spring.interceptor;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.zkdg.utils.entity.AjaxEntity;
import org.zkdg.utils.util.JsonUtils;

/**
 * 
 * @author 
 * @createData 2017年7月13日 下午12:27:19
 * @说明 :springMvc 异常处理
 */
// 注解,被spring 扫描到
@Component
public class ExInterceptor implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        // TODO Auto-generated method stub
        if (ex != null) {
            try {
                response.setStatus(200);
                Throwable cause = ex.getCause();
                if (cause == null) {
                    response.getWriter().write(JsonUtils.objectToJson(AjaxEntity.ERROR("<p style='color:red'>空指针异常</p> ")));
                } else if (cause instanceof SQLException) {
                    // json 输出
                    response.getWriter()
                            .write(JsonUtils.objectToJson(AjaxEntity.ERROR("数据库操作失败 : <p style='color:red'>" + cause.getMessage()+"</p>")));
                } else if (cause instanceof NullPointerException) {
                    response.getWriter()
                            .write(JsonUtils.objectToJson(AjaxEntity.ERROR("空指针异常 : <p style='color:red'>" + cause.getMessage()+"</p>")));
                }

                else {
                    response.getWriter()
                            .write(JsonUtils.objectToJson(AjaxEntity.ERROR("未知异常 : <p style='color:red'>" + cause.getMessage()+"</p>")));
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block

                e.printStackTrace();
            }

        }
        ex.printStackTrace();
        // 返回一个空的 modelandview(),必须返回,否则 异常处理配置无效。。
        return new ModelAndView();
    }

}


 

 不得不说,spring 是真的太强大了!!!!

原文地址:https://www.cnblogs.com/whm-blog/p/7159864.html