当前位置:网站首页>开发规范~参数校验异常、异常返回提示切面
开发规范~参数校验异常、异常返回提示切面
2022-06-24 19:38:00 【张子行的博客】
前言
曾几何时谁不是从一句 Hello Wrod 开始的秃头之旅呢,学习前期讲究代码能跑通就行,到了后期慢慢的开始去研究代码的优雅之道,什么设计模式啊、怎么使用最少的代码去实现一个功能。本文的内容在于帮助开发人员高效的对参数进行校验。
谏言
越简单的代码越高效,这个是我上岗遇到的第一个 IT 师傅说的,现已牢记于心也送给大家,不喜勿喷哦。
参数校验高级处理
直接编写环切的切面作用于参数校验不通过的异常就行,用到的就是 @ControllerAdvice 这个注解,至于 @ControllerAdvice 的生效时机,在我之前剖析Spring Mvc 源码的时候里面有详细的介绍。传送门
@Slf4j
@ControllerAdvice
@ResponseBody
public class MethodArgumentNotValidHandel {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public Result MethodArgumentNotValidHandler(HttpServletRequest request, MethodArgumentNotValidException exception){
JSONObject errorMsg = new JSONObject();
for (FieldError error : exception.getBindingResult().getFieldErrors()) {
errorMsg.putOnce(error.getField(), error.getDefaultMessage());
log.error(request.getRequestURI() + " 参数校验错误:" + errorMsg);
}
return Result.failed(exception.getBindingResult().getFieldError().getDefaultMessage());
}
}
参数校验
直接在接口的接受参数上加上 @Validated 注解即可。至于校验
然后在TrainOrder上对需要校验的字段,加上注解校验即可,message为异常提示信息。
效果
当存在校验不通过的字段时,会返回该字段的异常提示信息,直至全部校验通过
边栏推荐
猜你喜欢

ACL (access control list) basic chapter - Super interesting learning network

Idea global search replace shortcut key

envoy获取客户端真实IP

网上立案流程

The ktp900f mobile download program of the fail safe mobile panel prompts that the download cannot be performed, and the target device is running or not in the transmission mode

How to automatically remove all . orig files in Mercurial working tree?

Power system | IEEE paper submission process

Data center basic network platform

NIO多路复用之Selector的使用

Redis-跳表
随机推荐
How to compare two or more distributions: a summary of methods from visualization to statistical testing
Future development of education industry of e-commerce Express
NiO zero copy
Why can some programmers get good offers with average ability?
Leetcode: calculate the number of elements less than the current element on the right (sortedlist+bisect\u left)
Data center basic network platform
find your present (2)
Code farmers should also understand the IPv4 subnet division of point networks
Servlet详解
CA Zhouji - the first lesson in 2022 rust
NIO 零拷贝
Technology inventory: Technology Evolution and Future Trend Outlook of cloud native Middleware
Publicity of the second batch of shortlisted enterprises! Annual Top100 smart network supplier selection
YGG 近期游戏合作伙伴一览
What aspects should we start with in the feasibility analysis of dry goods?
Data communication and physical network
第二批入围企业公示!年度TOP100智能网联供应商评选
Certificate photo processing
STP spanning tree protocol Foundation
Docker 安装 MySQL 8.0,详细步骤