使用 @ExceptionHandler 进行异常处理

使用 @ExceptionHandler 进行异常处理

Spring MVC 提供一种机制,可以在控制器中通过 @ExceptionHandler 注解捕获当前控制器内方法抛出的异常,并统一处理。

@ExceptionHandler // 注解到方法上,出现异常时会执行该方法
public ModelAndView exceptionHandler(Exception ex){
    ModelAndView mv = new ModelAndView("error");
    mv.addObject("exception", ex);
    System.out.println("发现异常");
    return mv;
}

@RequestMapping("/error")
public String error(){
    int i = 10 / 0;
    return "hello";
}Code language: PHP (php)

自定义错误页面与异常信息呈现

添加 error.jsp 视图文件:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    错误消息:${exception.getMessage()}
</body>
</html>Code language: HTML, XML (xml)

在异常处理方法中可以指定使用哪个视图,并将异常对象传递给视图:

@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex){
    ModelAndView mv = new ModelAndView("error");
    mv.addObject("exception", ex);
    mv.setViewName("error");
    System.out.println("发现异常");
    return mv;
}Code language: PHP (php)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注