当前位置:网站首页>Development specification - parameter verification exception, exception return prompt section

Development specification - parameter verification exception, exception return prompt section

2022-06-24 22:45:00 Zhang Zixing's blog

Preface

Once upon a time, who did not start from a sentence Hello Wrod The beginning of the bald journey , In the early stage of learning, you should pay attention to that the code can run smoothly , In the later stage, I began to study the elegant way of code , What design pattern 、 How to use the least code to implement a function . The content of this article is to help developers verify parameters efficiently .

Remonstrance

The simpler the code, the more efficient , This is the first one I met on duty IT Shifu said , Now I have kept it in mind and give it to you , Don't spray if you don't like it .

Advanced processing of parameter verification

Directly write the tangent plane of the loop cut to act on exceptions that fail the parameter verification , What we use is @ControllerAdvice This annotation , as for @ControllerAdvice Time to take effect , Before I dissect Spring Mvc There is a detailed introduction to the source code . Portal

@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() + "  Parameter check error :" + errorMsg);
        }
        return Result.failed(exception.getBindingResult().getFieldError().getDefaultMessage());
    }
}

Parameter checking

Add... Directly to the accepted parameters of the interface @Validated Annotations can be . As for verification
 Insert picture description here
And then in TrainOrder On the field to be verified , Add notes to verify ,message Is an exception prompt .
 Insert picture description here

effect

When there are fields that fail the verification , The exception prompt information of this field will be returned , Until all the verification passes

原网站

版权声明
本文为[Zhang Zixing's blog]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241646375472.html