zoukankan      html  css  js  c++  java
  • 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 是真的太强大了!!!!

  • 相关阅读:
    LeetCode 【1】 Two Sum --001
    计算机网络-自定向下方法之应用层
    Android TextView自动换行、排列错乱问题及解决
    Android ScrollView内部组件设置android:layout_height="fill_parent"无效的解决办法
    Gson解析空字符串异常的处理
    AndroBench手机性能测试
    使用adb命令通过IP地址连接手机
    Android string.xml 添加特殊字符
    Android string资源 包含 数学符号等特殊字符 及 参数占位符
    Android Studio多渠道打包(二)
  • 原文地址:https://www.cnblogs.com/whm-blog/p/7159864.html
Copyright © 2011-2022 走看看