ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 概述 controller调用service,service调用dao,异常都是向上抛出的,最终DispatcherServlet找异常处理器进行异常的处理.如果没有异常处理器,就会将异常显示到页面上. ## 流程 ![](https://box.kancloud.cn/e5e5f433932137b902f7b3346f1adb75_1304x608.png) ## 默认情况 页面会显示异常,这样很不友好.应该有异常调跳转到错误页面. ~~~ @RequestMapping("index") public String index() { int a = 10 / 0; //模拟异常 return "success"; } ~~~ ![](https://box.kancloud.cn/1a1b9fe4ba261cdf08392b2b26ac6c49_2520x1050.png) ## 步骤 1. 自定义异常类(做提示信息的). 2. 编写异常处理器. 3. 配置异常处理器(跳转到提示页面). ## 代码 自定义异常类: ~~~ package com.like.exception; //自定义异常类 public class MyException extends Exception { //存储提示信息 private String message; public MyException(String message) { this.message = message; } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } ~~~ 自定义异常处理器: ~~~ package com.like.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 MyExceptionResolver implements HandlerExceptionResolver { //当控制器有异常跑出来,配置的异常处理器就会调用此类 @Override //Object o是当前处理器的对象.Exception e是控制器抛出的异常 public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { //处理异常逻辑 //获取异常对象 MyException ex = null; if (e instanceof MyException) { ex = (MyException) e; } else { e = new MyException("系统正在维护..."); } ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("errMsg", e.getMessage()); modelAndView.setViewName("error"); return modelAndView; } } ~~~ SpringMVC配置文件: ~~~ <bean id="myException" class="com.like.exception.MyExceptionResolver"></bean> ~~~ 错误页面: ~~~ <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> ${errMsg} </body> </html> ~~~ 控制器部分: ~~~ @RequestMapping("index") public String index() throws MyException { try { //模拟异常 int a = 10 / 0; } catch (Exception e) { //打印异常信息 e.printStackTrace(); //抛出自定义异常 throw new MyException("查询错误"); } return "success"; } ~~~