(九)springboot实战——springboot3下的webflux项目参数验证及其全局参数验证异常处理

前言

在上一节内容中,我们介绍了如何在webflux项目中自定义实现一个全局的异常处理器ErrorWebExceptionHandler,正常情况下其可以处理我们系统的运行时异常,但是无法处理参数验证的异常WebExchangeBindException,所以这里提供另外的全局异常处理方式,通过注解@ExceptionHandler实现参数验证的全局异常处理。

本节内容主要是实现webflux项目集成spring-boot-starter-validation验证框架,完成请求接口参数的后台验证,实现接口请求参数的统一验证处理,返回统一的响应数据格式。

正文

①引入请求参数验证框架spring-boot-starter-validation

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

②创建全局的参数验证异常处理器GlobalExceptionHandler

java 复制代码
package com.yundi.atp.exception;

import com.yundi.atp.common.ApiResponse;
import com.yundi.atp.common.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 参数验证异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(WebExchangeBindException.class)
    public Mono<ApiResponse> handleWebExchangeBindException(WebExchangeBindException ex) {
        log.info("参数验证异常:" + ex);
        // 处理绑定异常
        BindingResult result = ex.getBindingResult();
        List<FieldError> fieldErrors = result.getFieldErrors();
        return Mono.just(ApiResponse.fail(ErrorCode.WEB_EXCHANGE_BIND_ERROR.getCode(), fieldErrors.get(0).getDefaultMessage()));
    }

    /**
     * 数学计算异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(ArithmeticException.class)
    public Mono<ApiResponse> handleArithmeticException(ArithmeticException ex) {
        log.info("数学计算异常:" + ex);
        return Mono.just(ApiResponse.fail(ErrorCode.ARITHMETIC_ERROR.getCode(), ErrorCode.ARITHMETIC_ERROR.getMsg()));
    }

    /**
     * 自定义异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MyException.class)
    public Mono<ApiResponse> handleMyException(MyException ex) {
        log.info("自定义异常:" + ex);
        return Mono.just(ApiResponse.fail(ex.getCode(), ex.getMessage()));
    }

    /**
     * 兜底异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Mono<ApiResponse> handleMyException(Exception ex) {
        log.info("系统异常:" + ex);
        return Mono.just(ApiResponse.fail(ErrorCode.SYSTEM_ERROR.getCode(), ErrorCode.SYSTEM_ERROR.getMsg()));
    }
}

③ ErrorCode统一定义错误码,方便根据相关错误码处理业务

java 复制代码
package com.yundi.atp.common;


public enum ErrorCode {
    SYSTEM_ERROR(10000, "系统错误!"),
    ARITHMETIC_ERROR(10001, "数学计算异常!"),
    WEB_EXCHANGE_BIND_ERROR(10002, "参数验证异常!"),
    ;


    private Integer code;
    private String msg;

    ErrorCode(Integer code, String message) {
        this.code = code;
        this.msg = message;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

④以新增用户数据为例,增加用户数据的验证

java 复制代码
package com.yundi.atp.entity;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;


@Schema(name = "User", description = "用户类")
@Table(name = "user")
@Data
public class User {
    @Id
    @Schema(name = "id", description = "用户ID")
    private Integer id;

    @NotBlank(message = "用户名称不得为空!")
    @Schema(name = "name", description = "用户名称")
    private String name;

    @NotNull(message = "用户年龄不得为空!")
    @Schema(name = "age", description = "用户年龄")
    private Integer age;
}

⑤在保存用户请求接口中使用@Valid注解,开启请求参数验证

⑥ 启动webflux应用,使用swagger工具测试保存用户接口,验证参数注解生效,并按照统一响应格式返回了数据

⑦ 验证用户年龄的参数不为空

⑧ swagger需要使用专属webflux的springdoc-openapi-starter-webflux-ui启动器

<!-- https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-starter-webflux-ui -->
<dependency>
	<groupId>org.springdoc</groupId>
	<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
	<version>2.3.0</version>
</dependency>

结语

关于webflux项目的请求参数验证,以及统一的参数验证异常处理的内容到这里就结束了,我们下期见。。。

相关推荐
IT毕设梦工厂3 小时前
计算机毕业设计选题推荐-在线拍卖系统-Java/Python项目实战
java·spring boot·python·django·毕业设计·源码·课程设计
是梦终空4 小时前
JAVA毕业设计176—基于Java+Springboot+vue3的交通旅游订票管理系统(源代码+数据库)
java·spring boot·vue·毕业设计·课程设计·源代码·交通订票
工业互联网专业5 小时前
毕业设计选题:基于springboot+vue+uniapp的驾校报名小程序
vue.js·spring boot·小程序·uni-app·毕业设计·源码·课程设计
无名指的等待7125 小时前
SpringBoot中使用ElasticSearch
java·spring boot·后端
.生产的驴6 小时前
SpringBoot 消息队列RabbitMQ 消费者确认机制 失败重试机制
java·spring boot·分布式·后端·rabbitmq·java-rabbitmq
AskHarries6 小时前
Spring Boot利用dag加速Spring beans初始化
java·spring boot·后端
苹果酱05677 小时前
一文读懂SpringCLoud
java·开发语言·spring boot·后端·中间件
掐指一算乀缺钱7 小时前
SpringBoot 数据库表结构文档生成
java·数据库·spring boot·后端·spring
飞翔的佩奇8 小时前
xxl-job适配sqlite本地数据库及mysql数据库。可根据配置指定使用哪种数据库。
数据库·spring boot·mysql·sqlite·xxl-job·任务调度
luoluoal10 小时前
java项目之基于Spring Boot智能无人仓库管理源码(springboot+vue)
java·vue.js·spring boot