使用场景:当浏览器向浏览器发送请求,而服务器处理请求出现了异常的状况,若是直接把错误信息给浏览器展现出来是很很差的,由于用户就能看到具体的代码错误信息。因此当出现异常状况时,服务器能够给用户一个本次请求异常的页面,让用户知道当前服务器有点问题,请稍后再试。spring
public class MyException extends RuntimeException{ private String message; public MyException(){} public MyException(String message){ this.message = message; } public void setMessage(String message) { this.message = message; } @Override public String getMessage() { return message; } }
2)自定义异常处理类,处理咱们抛出的异常浏览器
@Component public class ExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { if (e instanceof MyException){ ModelAndView mv = new ModelAndView(); mv.addObject("errorMessage", e.getMessage()); mv.setViewName("error.jsp"); return mv; } return null; } }
@Controller public class UserController { @RequestMapping("testException.do") public String testException(){ try { String str = null; str.length(); }catch (NullPointerException e){ e.printStackTrace(); throw new MyException("服务器繁忙,请稍后再试!!!"); } return "testException.jsp"; } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 开启spring注解驱动--> <context:component-scan base-package="com.cjh"/> <!-- 开启mvc注解驱动--> <mvc:annotation-driven></mvc:annotation-driven> </beans>