• 创建自定义异常类及封装web返回对象


    1. 创建自定义异常类

    选择继承RuntimeException父类而不选择Exception:后者类型的异常需要我们手动显式处理,要么try catch ,或者throw到上一层进行处理,而前者类型的异常可以进行隐式处理,节省了我们很多的手动处理异常的麻烦

    package com.example.emos.wx.exception;
    import lombok.Data;
    @Data
    public class EmosException extends RuntimeException{
        private String msg;
        private int code = 500;
    
        public EmosException(String msg) {
            super(msg);
            this.msg = msg;
        }
    
        public EmosException(String msg, Throwable e) {
            super(msg, e);
            this.msg = msg;
        }
    
        public EmosException(String msg, int code) {
            super(msg);
            this.msg = msg;
            this.code = code;
        }
    
        public EmosException(String msg, int code, Throwable e) {
            super(msg, e);
            this.msg = msg;
            this.code = code;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    2. 封装web返回对象

    统一标准,保证所有controller返回的数据格式一致
    由于apache的httpcomponents库中的HttpStatus类封装了很多的状态码,我们可以利用这些状态码封装到返回的对象中。

    <dependency>
    	<groupId>org.apache.httpcomponents</groupId>
    	<artifactId>httpcore</artifactId>
    	<version>4.4.13</version>
    </dependency>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    再创建封装类 R类

    package com.example.emos.wx.common.util;
    
    import org.apache.http.HttpStatus;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class R extends HashMap<String, Object> {
    
        public R() {
            put("code", HttpStatus.SC_OK);
            put("msg", "success");
        }
    
        public static R error() {
            return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
        }
    
        public static R error(String msg) {
            return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
        }
    
        public static R error(int code, String msg) {
            R r = new R();
            r.put("code", code);
            r.put("msg", msg);
            return r;
        }
    
        public static R ok(String msg) {
            R r = new R();
            r.put("msg", msg);
            return r;
        }
    
        public static R ok(Map<String, Object> map) {
            R r = new R();
            r.putAll(map);
            return r;
        }
    
        public static R ok() {
            return new R();
        }
    
        public R put(String key, Object value) {
            super.put(key, value);
            return this;
        }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    3. 利用Swagger创建Api文档

    1. 配置依赖
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    1. 创建swagger配置类,初始化swagger
    package com.example.emos.wx.config;
    
    import io.swagger.annotations.ApiOperation;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.ApiKey;
    import springfox.documentation.service.AuthorizationScope;
    import springfox.documentation.service.SecurityReference;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spi.service.contexts.SecurityContext;
    import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @Configuration
    //启用swagger文档
    @EnableSwagger2
    public class SwaggerConfig {
        @Bean
        public Docket createRestApi() {
            Docket docket = new Docket(DocumentationType.SWAGGER_2);
    
            // ApiInfoBuilder 用于在Swagger界面上添加各种信息
            ApiInfoBuilder builder = new ApiInfoBuilder();
            builder.title("EMOS在线办公系统");
            ApiInfo apiInfo = builder.build();
            docket.apiInfo(apiInfo);
    
            // ApiSelectorBuilder 用来设置哪些类中的方法会生成到REST API中
            ApiSelectorBuilder selectorBuilder = docket.select();
            selectorBuilder.paths(PathSelectors.any()); //所有包下的类
            //使用@ApiOperation的方法会被提取到REST API中
            selectorBuilder.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));
            docket = selectorBuilder.build();
            /*
             * 下面的语句是开启对JWT的支持,当用户用Swagger调用受JWT认证保护的方法,
             * 必须要先提交参数(例如令牌)
             */
            //存储用户必须提交的参数
            List<ApiKey> apikey = new ArrayList();
            //规定用户需要输入什么参数
            apikey.add(new ApiKey("token", "token", "header"));
            docket.securitySchemes(apikey);
    
            //如果用户JWT认证通过,则在Swagger中全局有效
            AuthorizationScope scope = new AuthorizationScope("global", "accessEverything");
            AuthorizationScope[] scopeArray = {scope};
            //存储令牌和作用域
            SecurityReference reference = new SecurityReference("token", scopeArray);
            List refList = new ArrayList();
            refList.add(reference);
            SecurityContext context = SecurityContext.builder().securityReferences(refList).build();
            List cxtList = new ArrayList();
            cxtList.add(context);
            docket.securityContexts(cxtList);
    
            return docket;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68

    其中常用的注解:

    • @ApiModel:用来对类进行描述
    • @ApiModelProperty:用来对类中的属性进行描述
    • @Api:一般作用在controller类上,说明类的作用
    • @ApiOperation:作用在方法上用来对方法进行说明
  • 相关阅读:
    FreeRTOS入门教程(任务状态)
    【源码课件+教程】Python入门教程_Python400集持续更新
    R语言并行计算提高速度丨parallel包和foreach包
    ArduPilot飞控AOCODARC-H7DUAL固件编译
    手把手教你实现一个流动的渐变色边框
    Java IO流与文件(二)
    web 面试高频考点 —— JavaScript-Web-API 篇(二)AJAX、存储
    ChatGPT的强大之处:探究及与国内产品的对比
    居然可以像玩游戏一样学Git
    关于使用后端实现动态表单功能的心得
  • 原文地址:https://blog.csdn.net/weixin_45627193/article/details/126466679