当前位置:网站首页>开发规范~参数校验异常、异常返回提示切面
开发规范~参数校验异常、异常返回提示切面
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为异常提示信息。
效果
当存在校验不通过的字段时,会返回该字段的异常提示信息,直至全部校验通过
边栏推荐
- 为什么有的程序员能力一般却能拿到好offer?
- Layer 2 and layer 3 forwarding principle based on VLAN
- 干货丨产品的可行性分析要从哪几个方面入手?
- A pit in try with resources
- Programmers become gods by digging holes in one year, carrying flags in five years and becoming gods in ten years
- 华大4A0GPIO设置
- 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
- Can AI chat robots replace manual customer service?
- Data communication and physical network
- Heartless sword Chinese English bilingual poem 003 The sea of books
猜你喜欢

FANUC机器人_KAREL编程入门学习(1)
Relationnet++: a representation of fusion of multiple detection targets based on transformer | neurips 2020

关于自动控制原理资料更新

YGG recent game partners list

Can AI chat robots replace manual customer service?

Creating files, recursively creating directories

NIO、BIO、AIO

系统测试主要步骤

电力系统| IEEE论文投稿流程

Heavyweight! Fada is listed as a "specialized and new" enterprise
随机推荐
NIO多路复用之Selector的使用
CA Zhouji - the first lesson in 2022 rust
CDN principle
Data communication foundation - Ethernet port mirroring and link aggregation
如何比较两个或多个分布:从可视化到统计检验的方法总结
中国SSD行业企业势力全景图
Zero code can apply data visualization to enterprise management
进程的通信方式
CDN principle
Data center basic network platform
Virtual private network foundation
A pit in try with resources
Creating files, recursively creating directories
A girl has been making hardware for ten years. 。。
Genesis公链与美国一众加密投资者齐聚Consensus 2022
Data communication and physical network
Leetcode: push domino (domino simulation)
Principle of IP routing
find your present (2)
NIO 零拷贝