多学习。

SpringMVC异常处理

分析

为防止异常直接显示在浏览器上,我们需要一个异常处理器,转到错误提示页面。

实现

1.编写自定义异常类(做提示信息的)

package com.czy.exception;

/**
 * 自定义异常类
 */

public class SysException extends Exception{

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

    public SysException(String message){
        setMessage(message);
    }

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

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

2.捕获异常并抛出自定义异常

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

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


        return "success";
    }

3.编写异常处理器

package com.czy.exception;

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
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        //获取异常对象
        SysException sysException = null;

        if(e instanceof SysException) sysException = (SysException)e;
        else sysException = new SysException("系统正在维护");

        ModelAndView mv = new ModelAndView();
        mv.addObject("errorMsg",sysException);
        mv.setViewName("error");

        return mv;
    }
}

4.编写提示信息页面

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

5.配置异常处理器(跳转到提示页面)

<!--配置异常处理器-->
    <bean id="sysExceptionResolver" class="com.czy.exception.SysExceptionResolver"></bean>
posted @   czyaaa  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示