zoukankan      html  css  js  c++  java
  • spring mvc 和mybatis整合 的异常处理

    1.自定义异常信息类 通过构造函数来实现异常信息的接收

    public class CustomException extends Exception {

    //异常信息
    private String message;

    public CustomException (String message){
    super(message);
    this.message = message;
    }
    public String getMessage() {
    return message;
    }

    public void setMessage(String message) {
    this.message = message;
    }

    }

    2.通过实现HandlerExceptionResolver的接口来实现异常处理  流程:先是解析异常,再判断是否是系统自定义异常,如果是就直接抛出异常,如果不是自定义异常就直接构造一个自定义的异常类型(信息为“未知错误,请与管理员联系!”)

    //不是自定义饿异常多半是运行异常,尽量在测试的时候就解决掉

    public class CustomExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
    HttpServletResponse response, Object handler, Exception ex) {


    CustomException customException=null;
    if(ex instanceof CustomException ){
    customException = (CustomException)ex;
    }else{
    customException = new CustomException("未知错误,请与管理员联系!");
    }
    //获取错误信息
    String message = customException.getMessage();
    System.out.println("异常信息:"+message);
    //创建ModelAndView对象
    ModelAndView modelAndView = new ModelAndView();
    //把错误信息填充到request域中
    modelAndView.addObject("message", message);
    //传入到页面
    modelAndView.setViewName("error");
    return modelAndView;
    }

    }

    3.在spring 的xml文件中配置 class 是CustomExceptionResolver的路径

    <!-- 异常处理器 -->
    <bean class="com.menglin.ssm.exception.CustomExceptionResolver"></bean>

     4.开始测试  (需求:当在查询的时候如果信息不存在的时候就抛出异常 )

    /**
    * 根据id来查询
    */
    @Override
    public ItemsCustom findItemsCustomById(Integer id) throws Exception {
    ItemsCustom itemsCustom = null;
    Items items = itemsMapper.selectByPrimaryKey(id);
    if(items==null){

    throw new CustomException("商品信息不存在!");
    }else{
    itemsCustom = new ItemsCustom();
    BeanUtils.copyProperties(items, itemsCustom);
    }
    return itemsCustom;

    }

    5.错误信息的展示

  • 相关阅读:
    MongoDB 时间截取、字符串截取、拼接(时间戳、字符串等)
    ClickHouse 参数配置
    C++函数调用栈的变化分析
    WPF中为button添加快捷键(ShortCut)的方法
    vscode中一些好用的插件介绍
    剑指Offer 2. 青蛙跳台阶问题
    切片Slice的使用
    剑指Offer 1. 斐波那契数列
    match_parent和wrap_content的区别
    字节流、字符流
  • 原文地址:https://www.cnblogs.com/lemon863376328/p/5010049.html
Copyright © 2011-2022 走看看