程序员社区

SpringMvc中异常处理

在这里插入图片描述

文章目录

    • 1.写一个前端页面
    • 2.写后台代码
    • 3.写一个跳转页面
    • 4. 使用SpringMvc处理异常
      • 4.1 编写一个自定义异常处理类(提示信息)
      • 4.2 编写异常处理器
      • 4.3 配置异常处理器

1.写一个前端页面

<h3>异常处理</h3>
<a href="user/testException">testException....</a>

2.写后台代码

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/testException")
    public String testException() throws Exception{
        System.out.println("异常处理");

        //模拟异常
        int a = 10/0;
        return "success";
    }
}

3.写一个跳转页面

<h3>执行成功</h3>

在这里插入图片描述
报了一个异常:
在这里插入图片描述

4. 使用SpringMvc处理异常

4.1 编写一个自定义异常处理类(提示信息)

public class SystemException extends Exception {
    //存储提示信息
    private String message;
    public SystemException(String message) {
        this.message = message;
    }
    @Override
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

4.2 编写异常处理器

当出现异常时,前端控制器会调用异常处理器,然后处理异常。。。

public class SYSExceptionResolve implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        //获取异常对象
        SystemException e = null;
        if(ex instanceof SystemException){
            e=(SystemException)ex;
        }else{
            e = new SystemException("系统正在维护。。。");
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("errormsg",e.getMessage());
        mv.setViewName("error");
        return mv;
    }
}

4.3 配置异常处理器

<!--配置异常处理器-->
<bean id="systemExceptionResolver" class="com.hh.exception.SYSExceptionResolve"/>

在这里插入图片描述

赞(0) 打赏
未经允许不得转载:IDEA激活码 » SpringMvc中异常处理

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区