Spring Boot 使用 @ControllerAdvice 注解处理全局异常
Spring Boot Java 大约 1308 字指定异常
可根据异常类型返回对应信息。如使用了@Valid
注解进行请求字段的验证,可判断异常是否是MethodArgumentNotValidException
来返回对应的信息。
也可自定义异常,只需根据相应类型判断返回对应错误信息即可。
代码示例
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public Result handleException(Exception e) {
log.error("GlobalExceptionHandler#{}", e.getMessage());
Result result = new Result();
result.setCode(-1);
if (e instanceof MethodArgumentNotValidException) {
BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
String defaultMessage = "参数校验未通过";
if (bindingResult.hasErrors()) {
defaultMessage = ":" + bindingResult.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
}
result.setMsg(defaultMessage);
} else if (e instanceof MissingServletRequestParameterException) {
result.setMsg("请求参数不完整");
}else if (e instanceof TypeMismatchException) {
result.setMsg("请求参数类型不匹配");
} else if (e instanceof HttpMessageNotReadableException) {
result.setMsg("缺少请求体参数");
} else {
result.setMsg("请求失败");
}
return result;
}
}
阅读 2390 · 发布于 2020-04-02
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓
昵称:
随便看看
换一批
-
23 种设计模式阅读 1997
-
Docker 运行结束后自动销毁容器阅读 1815
-
PostgreSQL 查询表中的自增序列名称阅读 5663
-
npm Hostname/IP does not match certificate's altnames阅读 3594
-
Java 后端面试题汇总阅读 908
-
ThinkPHP5 设置 Redis 长连接阅读 4605
-
Hyper-V Default Switch 无法联网解决办法阅读 6500
-
Kubernetes 数据存储 PV 和 PVC阅读 1320
-
Go 操作 PostgreSQL阅读 3987
-
Linux xxx is not in the sudoers file.This incident will be reported阅读 2717