zoukankan      html  css  js  c++  java
  • 峰哥说技术:13-Spring Boot ControllerAdvice处理全局异常

    Spring Boot深度课程系列

    峰哥说技术—2020庚子年重磅推出、战胜病毒、我们在行动

    13  峰哥说技术:Spring Boot ControllerAdvice处理全局异常

    ControllerAdvice是Controller的增强版,主要用于全局数据的处理,一般和@ExceptionHandler、@InitBinder、@ModelAttribute搭配使用。它并不属于Spring Boot的内容,而是Spring框架中本身就有该注解。一般来说@ExceptionHandler和该注解用在全局异常处理的时候用的比较多。所以我们这里重点讲解该注解处理全局异常。后面的两个用法大家可以到官网去查看,这里不做介绍。

    需求说明:我们使用文件上传案例,在application.properties中配置单个文件的上传大小的现在为1kb。当超过1kb图片的时候,抛出异常,我们进行全局异常的处理。

    1)构建异常,在application.properties中进行配置。

    spring.servlet.multipart.max-file-size=1KB

    2)测试,在http://localhost:8081/index.html,选择1个大于1kb的图片。

     

    这里的异常类型是FileSizeLimitExceededException。它含义是文件的大小超过极限异常。

    现在采用ControllerAdvice来处理。这里讲解两种方式,一种是响应异常信息文本。第二种返回到视图或者说ModelAndView。

    A)直接响应文本

    1)创建exception包,编写一个FileUploadException类

    @ControllerAdvice
    public class MyCustomException {
        @ExceptionHandler(MaxUploadSizeExceededException.class)
        public void FileUploadException(MaxUploadSizeExceededException e, HttpServletResponse response) throws IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write("上传文件大小超过限制");
            writer.flush();
            writer.close();
        }
    }

    2)测试,下面是结果:

     

    @ControllerAdvice添加到类后,当系统启动的时候会将对于的类扫描到Spring容器,MaxUploadSizeExceededException会处理上传的异常。当我们需要处理所有异常的时候可以将异常的类型换成Exception就可以了。

    返回值可以有,也可以没有,可以是JSON,也可以是ModelAndView。也可以是其他类型,这都很灵活。

    B)返回ModelAndView

    我们采用Thymeleaf作为视图组件,然后返回ModelAndView。步骤如下

    1)添加thymeleanf依赖。

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    2)templates下面创建myerror.html错误处理视图。

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h4 th:text="${error}"></h4>
    </body>
    </html>

    3)编写MyCustomException,并编写代码。

    @ControllerAdvice
    public class MyCustomException {
        @ExceptionHandler(MaxUploadSizeExceededException.class)
        public ModelAndView FileUploadException(MaxUploadSizeExceededException e) throws IOException {
            ModelAndView mv=new ModelAndView();
            mv.addObject("error","上传的文件超过限制大小,请注意");
            mv.setViewName("myerror");
            return mv;
        }
    }

    4)测试如下:

     

  • 相关阅读:
    ddd
    对Map按key和value分别排序
    两端通信
    WinDBG调试.NET程序示例
    FAQ:仓储实现为什么在基础设施层?
    Please Send Me a Card
    Web API 入门指南
    Node.js
    聊天工具mychat
    C语言面试问答5
  • 原文地址:https://www.cnblogs.com/027kgc/p/12502124.html
Copyright © 2011-2022 走看看