且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

spring boot 1.5.4 统一异常处理(九)

更新时间:2022-10-13 23:35:28


1      Spring Boot统一异常处理

Spring Boot中实现了默认的error映射,但是在实际应用中,上面你的错误页面对用户来说并不够友好,我们通常需要去实现我们自己的异常提示。

springboot项目为例,进行处理!

spring-boot相关项目源码,

码云地址:https://git.oschina.net/wyait/springboot1.5.4.git

github地址https://github.com/wyait/spring-boot-1.5.4.git



1.1  创建全局异常处理类

通过使用@ControllerAdvice定义统一的异常处理类,而不是在每个Controller中逐个定义。@ExceptionHandler用来定义函数针对的异常类型,最后将Exception对象和请求URL映射到error.html中(默认重定向到error.html页面,可自定义)

/**

 *

 * @项目名称:spring-boot-jsp

 * @类名称:GlobalExceptionHandler

 * @类描述:全局异常处理类

 * @创建人:wyait

 * @创建时间:2017628下午4:06:08

 * @version

 */

@ControllerAdvice

public classGlobalExceptionHandler {

   publicstatic final String DEFAULT_ERROR_VIEW = "error";

 

   @ExceptionHandler(value= Exception.class)

   publicModelAndView defaultErrorHandler(HttpServletRequest req, Exception e)

        throwsException {

      ModelAndViewmav = new ModelAndView();

      mav.addObject("exception",e);

      mav.addObject("url",req.getRequestURL());

      mav.setViewName(DEFAULT_ERROR_VIEW);

      returnmav;

   }

}

1.2  编写error.html

templates目录下创建error.html,将请求的URLException对象的message输出。

<!DOCTYPE html>

<html>

<head>

<metacharset="UTF-8"/>

<title>This is Exceptionhtml</title>

</head>

<body>

   <h1>ErrorHandler</h1>

   <divth:text="${url}"></div>

   <divth:text="${exception.message}"></div>

</body>

</html>

HelloController里添加:1/0代码。

启动,访问:

spring boot 1.5.4 统一异常处理(九)

如果没有exception异常,比如:404,页面效果是:

spring boot 1.5.4 统一异常处理(九)

 

通过实现上述内容之后,我们只需要在Controller中抛出Exception,当然我们可能会有多种不同的Exception。然后在@ControllerAdvice类中,根据抛出的具体Exception类型匹配@ExceptionHandler中配置的异常类型来匹配错误映射和处理。

 



本文转自 wyait 51CTO博客,原文链接:http://blog.51cto.com/wyait/1969162,如需转载请自行联系原作者