zoukankan      html  css  js  c++  java
  • springmvc异常处理

    1.创建一个异常类

    /**
    * 自定义异常类
    */
    public class SysException extends Exception{

    //存储提示信息
    private String message;

    @Override
    public String getMessage() {
    return message;
    }

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

    public SysException(String message) {
    this.message = message;
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    2.conteoller控制类

    @Controller
    @RequestMapping("/user")
    public class UserConteoller {

    @RequestMapping("/testException")
    public String testException() throws SysException {
    System.out.println("Exception执行了..");

    //模拟异常
    try {
    int a = 10 / 0;
    } catch (Exception e) {
    //打印异常信息
    e.printStackTrace();
    //抛出自定义异常信息
    throw new SysException("查询所有用户出现错误...");
    }

    return "success";
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    3.异常处理器类

    /**
    * 异常处理器
    */
    public class SysExceotionResolver implements HandlerExceptionResolver {

    /**
    * 处理异常的业务逻辑
    * @param httpServletRequest
    * @param httpServletResponse
    * @param
    * @param
    * @return
    */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception ex) {
    //获取到异常对象
    SysException e = null;
    if(ex instanceof SysException){
    e = (SysException)ex;
    }else{
    e = new SysException("系统正在维护");
    }
    //创建 ModelAndView对象
    ModelAndView mv = new ModelAndView();
    mv.addObject("errorMsg",e.getMessage());
    mv.setViewName("error");
    return mv;
    }
    }
    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
    4.配置

    <!--配置异常处理器-->
    <bean id="sysExceotionResolver" class="sise.cn.exception.SysExceotionResolver"></bean>
    1
    2
    5.创建error.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
    <html>
    <head>
    <title>Title</title>
    </head>
    <body>

    ${errorMsg}
    </body>
    </html>

  • 相关阅读:
    USACO 玛丽卡(最短路+枚举)
    POJ 1161 Walls(最短路+枚举)
    Windows 上配置Docker Desktop 的k8s
    菜鸡学算法--70. 爬楼梯
    CLR 异步函数
    【.NET Core开发实战学习笔记】依赖注入框架:管理服务的依赖与生命周期
    【.NET Core 开发实战学习笔记】StartUp:理解程序的启动过程
    .ef core 多对对关系的关联方法
    HttpGet请求传递数组(集合)
    使用wkhtmltopdf工具生成pdf
  • 原文地址:https://www.cnblogs.com/ly570/p/10983117.html
Copyright © 2011-2022 走看看