• 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>

  • 相关阅读:
    排序——选择排序和插入排序
    排序——排序的基本概念
    字符串类——KMP算法的应用
    字符串类——KMP子串查找算法
    字符串类——字符串类的创建(下)
    字符串类——字符串类的创建(上)
    数据结构库——链式队列的实现
    P4180 【模板】严格次小生成树[BJWC2010]
    P2511 [HAOI2008]木棍分割
    P2613 【模板】有理数取余
  • 原文地址:https://www.cnblogs.com/ly570/p/10983117.html
Copyright © 2020-2023  润新知