使用Spring Validation实现参数校验
引入Spring Validation 起步依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId>
</dependency>
参数校验失败异常处理
所有的http请求异常都会被拦截处理
exception/GlobalExceptionHandler
package com.devops.exception;import com.devops.pojo.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;/*
* 全局异常处理器
* */
@RestControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public Result handlerException(Exception e) {e.printStackTrace();if (e == null || e.getMessage() == null || e.getMessage().isEmpty()) {return Result.error("操作失败");} else {return Result.error(e.getMessage());}}
}