当前端提供不合法的数据的时候,后端不能正常接受,就产生了bug,然后就导致了前端迟迟拿不到数据,所以我们可以在后端出现异常的时候做一个异常拦截,然后给前端返回提示的信息
代码如下
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/*
统一数据处理,异常处理
*/
@ControllerAdvice
public class ControllerExceptionHandler {
//打印日志
private static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionHandler.class);
/**
* 校验异常统一处理
* @param e
* @return
*/
//这里的BindException就是上文提到的出现的异常
@ExceptionHandler(value = BindException.class)
@ResponseBody
public CommonResp validExceptionHandler(BindException e) {
//CommonResp是我自己定义的一个返回数据的类
CommonResp commonResp = new CommonResp();
LOG.warn("参数校验失败:{}", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
commonResp.setSuccess(false);
commonResp.setMessage(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return commonResp;
}
}
需要导入的依赖
<!-- validation做参数校验-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
在spring boot中我们只需要写好这个类就可以了,不需要我们自己去主动使用它,是spring boot 框架自己去用它,spring boot会扫描到这些注解,这就是spring boot的强大和好用之处
本文介绍了如何在SpringBoot应用中处理后端异常,通过创建`ControllerExceptionHandler`类并使用`@ControllerAdvice`和`@ExceptionHandler`注解进行全局异常捕获。当前端传递非法数据导致BindException时,后端将返回自定义的错误信息。通过引入`spring-boot-starter-validation`依赖,实现参数校验,并返回给前端友好的提示。这样增强了系统的健壮性和用户体验。
4428

被折叠的 条评论
为什么被折叠?



