springboot统一异常处理

绝地灬酷狼 2022-05-16 00:15 402阅读 0赞

创建全局异常处理类:通过使用@ControllerAdvice定义统一的异常处理类,@ExceptionHandler用来定义针对的异常类型

1.增加异常类:

  1. @ControllerAdvice
  2. class GlobalExceptionHandler {
  3. @ExceptionHandler(value = Exception.class)
  4. public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e)
  5. throws Exception {
  6. ModelAndView mav = new ModelAndView();
  7. mav.addObject("msg", "异常咯...");
  8. mav.setViewName("error");
  9. return mav;
  10. }
  11. }

2.增加Controller方法,抛出异常:

  1. @RequestMapping("/exception")
  2. public String hello() throws Exception {
  3. throw new Exception("发生错误");
  4. }

3.src/main/resources/templates增加error.html:

  1. <!DOCTYPE html>
  2. <html>
  3. <head lang="en">
  4. <meta charset="UTF-8" />
  5. <title>统一异常处理</title>
  6. </head>
  7. <body>
  8. <h1>Error</h1>
  9. <div th:text="${msg}"></div>
  10. </body>
  11. </html>

更多springboot相关知识参见[持续更新]

springboot教程目录

发表评论

表情:
评论列表 (有 0 条评论,402人围观)

还没有评论,来说两句吧...

相关阅读