springboot项目中使用assert来替换if逻辑,减少大量的无用代码,在api中只关注正确的返回值即可,其他的都以异常抛出处理。
常见异常有
MissingServletRequestParameterException:
是 Spring 框架中抛出的一个异常,表示客户端请求缺少一个必需的请求参数。这个异常通常在处理 HTTP 请求时发生,当使用 @RequestParam 注解标记的参数是必需的,但请求中没有提供该参数时,就会抛出这个异常。
MethodArgumentNotValidException
是 Spring 框架中抛出的一个异常,表示在控制器方法中验证的参数没有通过验证。这个异常通常在使用 @Valid 或 @Validated 注解进行参数验证时发生。
@PostMapping("/users")
public String createUser(@Valid @RequestBody User user) {
return "User created: " + user.getName();
}
IllegalArgumentException
是 Java 标准库中的一个异常类,表示方法接收到非法或不适当的参数。这个异常通常在方法或构造函数检测到无效的参数值时抛出。通过assert方法抛出的异常在这里捕捉处理
最后通过spring的注解@RestControllerAdvice 来注入到全局,定义一个result全局返回类型
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
// 请求参数缺失异常
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
public Result handler(MissingServletRequestParameterException e, HttpServletRequest request) {
log.error("url:{}, 缺少请求参数:----------------{}:{}",request.getRequestURI(), e.getLocalizedMessage(), e);
return Result.fail("缺少必要的请求参数");
}
// 实体校验异常捕获
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public Result handler(MethodArgumentNotValidException e, HttpServletRequest request) {
BindingResult result = e.getBindingResult();
ObjectError objectError = result.getAllErrors().stream().findFirst().get();
log.error("url:{}, 实体校验异常:----------------{}",request.getRequestURI(), objectError.getDefaultMessage());
return Result.fail("参数校验异常:"+objectError.getDefaultMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = IllegalArgumentException.class)
public Result handler(IllegalArgumentException e, HttpServletRequest request) {
log.error("url:{}, Assert异常:----------------{}", request.getRequestURI(), e.getLocalizedMessage(), e);
return Result.fail(e.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = RuntimeException.class)
public Result handler(RuntimeException e, HttpServletRequest request) {
log.error("url:{}, 运行时异常:----------------{}", request.getRequestURI(), e.getLocalizedMessage(), e);
if(e instanceof AccessDeniedException) {
return Result.fail(ResultCodeEnum.ACCESS_DENIED);
} else if(e instanceof BadSqlGrammarException) {
return Result.fail("运行时异常:SQL错误");
}
return Result.fail("运行时异常:" + e.getLocalizedMessage());
}
}