springmvc自定义异常处理器

6b450c3c818f46f2be772ec024d3e4f8

当dispatchServlet接收到controller抛出的异常时,会将异常交由 HandlerExceptionResolver

异常处理器处理!我们可以创建自定义异常处理器实现该接口来处理自定义异常

 

1) 自定义异常类

复制代码
public class MyException extends Exception {
    // 异常信息
    private String message;
 
    public MyException() {
       super();
    }
 
    public MyException(String message) {
       super();
       this.message = message;
    }
 
    public String getMessage() {
       return message;
    }
 
    public void setMessage(String message) {
       this.message = message;
    }
 
}
复制代码

 

2)自定义异常处理器

复制代码
public class CustomHandleException implements HandlerExceptionResolver {
 
    @Override
   public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
           Exception exception) {
       // 定义异常信息
       String msg;
 
       // 判断异常类型
       if (exception instanceof MyException) {
           // 如果是自定义异常,读取异常信息
           msg = exception.getMessage();
       } else {
           // 如果是运行时异常,则取错误堆栈,从堆栈中获取异常信息
           Writer out = new StringWriter();
           PrintWriter s = new PrintWriter(out);
           exception.printStackTrace(s);
           msg = out.toString();
 
       }
 
       // 把错误信息发给相关人员,邮件,短信等方式
       // TODO
 
       // 返回错误页面,给用户友好页面显示错误信息
       ModelAndView modelAndView = new ModelAndView();
       modelAndView.addObject("msg", msg);
       modelAndView.setViewName("error");
 
       return modelAndView;
    }
}
复制代码

 

3)在springmvc.xml中配置异常处理器

<!-- 配置全局异常处理器 -->
<bean
id="customHandleException" class="cn.itcast.ssm.exception.CustomHandleException"/>

 

4)定制错误页面

复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
    <h1>系统发生异常了!</h1>
    <br />
    <h1>异常信息</h1>
    <br />
    <h2>${msg }</h2>
 
</body>
</html>
复制代码

 

5)测试异常处理

复制代码
@RequestMapping(value = "/item/itemlist.action")
public ModelAndView itemList() throws MyException{
        
        List<Items> list = itemService.selectItemsList();
        
        if(true){
            throw new MyException("商品列表不能为空!!");
        }
        
        ModelAndView mav = new ModelAndView();
        mav.addObject("itemList", list);
        mav.setViewName("itemList");
        return mav;
    }
复制代码

 

9a4c08a5bf624c50bce967b981607779

posted @   青岑  阅读(843)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示
主题色彩