ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

springMVC-异常处理

2026/9/14 17:45:07 拓冰建站 浏览量
springMVC-异常处理

一、四种异常形式

在springmvc中,处理异常有四种形式
1.局部异常
2.全局异常
3.自定义异常
4.统一异常(统一提示异常)

作用:可以使浏览器不出现丑陋的500错误提示,而跳转到另外的错误提示页面

另外,自定义异常可以自定义异常的提示信息

二、局部异常

局部异常指的是:你发生异常,只有本类的目标方法中发生,才能捕获到

1、在一个handler中写一个捕获局部异常的方法

@Controller
public class MyExceptionHandler {@ExceptionHandler({ArithmeticException.class, NullPointerException.class})public String localException (Exception ex, HttpServletRequest request) {System.out.println("异常信息是~"+ex.getMessage());//如何将异常的信息带到下一个页面request.setAttribute("reson", ex.getMessage());return "exception";}@RequestMapping(value = "/testException")public String testException(Integer num) {int i = 9/num; //认为制造一个数学异常,令num等于0return "loginOK";}
}

2、 前端测试链接

<a href="testException/?num=0">测试局部异常</a>

3、异常测试页面

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head><title>Title</title>
</head>
<body>
<h1>你好,出现异常了</h1>
${reson}
</body>
</html>

4、效果

三、全局异常 

所谓全局异常,就是指的,不管在哪个Handler抛出的异常,都可以捕获

1、将刚才局部异常的那个异常方法注释掉,重新写一个

@ControllerAdvice // 全局异常处理
public class MyGlobalException {@ExceptionHandler({ArithmeticException.class, NullPointerException.class})public String localException (Exception ex, HttpServletRequest request) {System.out.println("异常信息是~"+ex.getMessage());//如何将异常的信息带到下一个页面request.setAttribute("reson", ex.getMessage());return "exception";}}

2、与局部异常的区别 就是重新写了一个类并用@ControlerAdvice修饰

四、自定义异常

根据自己项目的需要而定义的某个特别的异常(是程序员规定,比如UserNotFoundException)

1、测试页面

<a href="testException2">ceshi</a>

2、写自定义异常

@ResponseStatus(reason = "你的异常是",value = HttpStatus.BAD_REQUEST)
public class MyException extends RuntimeException{}

3、写handler

  @RequestMapping(value = "/testException2")public String testException2(Integer num) {throw new MyException();}

 4、效果(效果相当于你可以给出一个更详细的异常提示信息)

 

五、统一异常 

        即如果发生了某个异常,我们可以统一的配置一个视图,然后通过该视图显示信息即可。比如我们统一提供一个数组越界的异常页面。

1、测试页面,测试handler

<a href="testException3">ceshi统一异常simpleMappingExceptionResolver</a>
 //统一异常@RequestMapping(value = "/testException3")public String testException3(Integer num) {int[] arr = new int[]{1,2,3};System.out.println(arr[88]);  //此处将抛出一个数组越界异常return "loginOK";}

 

2、在springMVC配置

    <!--    配置统一异常--><bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"><property name="exceptionMappings"><props><prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop></props></property></bean>

3、错误提示页 error.jsp

<body>
你的数组越界了
</body>

4、效果​​​​​​​