自定义异常处理器

spring中自定义异常处理器

  • 前言
  • 二、使用步骤
    • 自定义异常处理器
    • 简单的错误页面


前言

网页抛出异常不是很友好,这时我们的项目需要一个处理器,做到项目后台出现异常,自动跳转到错误页面。


二、使用步骤

自定义异常处理器

步骤:
1. 自定义一个类实现HandlerExceptionResolver接口
2. 实现接口中的方法
3. 创建异常处理器的对象

@Component
public class CustomerExceptionResolver implements HandlerExceptionResolver {
     
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                         Object o, Exception e) {
     
        //1. 创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        //2. 保存异常信息到ModelAndView里面
        mv.addObject("errorMsg",e.getMessage());
        //3. 设置返回的视图页面名称
        mv.setViewName("error");
        return mv;
    }
}

简单的错误页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
    访问出现了异常:${errMsg}
body>
html>

你可能感兴趣的:(java后端,java)