SpringMVC的异常处理

异常处理的思路

1.在请求页面输入控制器地址

<%--
  Created by IntelliJ IDEA.
  User: 86187
  Date: 2021/3/4
  Time: 14:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>异常处理</h3>

    <a href="user/testException">异常处理</a>
</body>
</html>

2. 控制器设计

package cn.itcast.controller;

import cn.itcast.exception.SysException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.annotation.Retention;

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/testException")
    public String testException()throws SysException{
        System.out.println("testException方法执行了。。。");
        //模拟异常,捕获异常,并抛出自定义异常
        try {
            int a =10/0;
        } catch (Exception e) {
            //打印异常信息
            e.printStackTrace();
            //抛出自定义异常信息SysException
            throw new SysException("查询所有用户出现错误。。。");
        }
        return "success";
    }
}

3.自定义异常类

由于里面需要抛出新的异常throw new SysException,所以新建异常类:

package cn.itcast.exception;

import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 异常处理器的构造
 */
public class SysExceptionResolver implements HandlerExceptionResolver{


    /**
     * 处理异常业务逻辑
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @return
     */
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,  Object o, Exception e) {
        //获取到异常对象
        SysException ex = null;
        if(e instanceof SysException){
            ex = (SysException)e;
        }else {
            ex =new SysException("系统正在维护。。。");
        }
        //ModelAndView可以跳转某界面,创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        mv.addObject("errorMsg",ex.getMessage());
        mv.setViewName("error");
        return mv;
    }
}

4.设计跳转页面

在这个异常类中,我们设计其跳转error.jsp页面:

<%--
  Created by IntelliJ IDEA.
  User: 86187
  Date: 2021/3/4
  Time: 19:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    ${errorMsg}

</body>
</html>

运行即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值