傳參校驗@Valid及對其的異常捕獲
springboot參數(shù)經(jīng)常需要進行校驗,比如創(chuàng)建文件,文件名就需要進行一定的校驗。
本文以創(chuàng)建文件夾為例進行參數(shù)校驗:controller:
首先就是在需要校驗的參數(shù)類前面添加注釋@Valid
1
2
3
4
5
6
7
8
9
|
@ApiOperation (value = "創(chuàng)建目錄" , notes = "在某目錄下創(chuàng)建新文件夾" ) @ApiResponses ({ @ApiResponse (code = 500 , response = RestCodeMsg. class , message = "錯誤" ) }) @PostMapping (value = "api/scene/createdir" ) public ResponseEntity<Map> createNewOrEditFile( @RequestBody @Valid ixviewVo ixveVo) { .... //校驗與內(nèi)容無關(guān) } |
其次對參數(shù)類進行校驗設(shè)置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Data @ApiModel @Getter @Setter @NoArgsConstructor public class ixviewVo { @ApiModelProperty ( "是否文件夾" ) private boolean dir; @NotBlank (message= "目錄名稱不能為空" ) @Pattern (regexp= "[^\\s\\\\/:\\*\\?\\\"<>\\|\\.]*[^\\s\\\\/:\\*\\?\\\"<>\\|\\.]$" ,message= "目錄名稱不符合標準" ) @ApiModelProperty ( "目錄名稱" ) private String dirname; @ApiModelProperty ( "上級目錄ID" ) private Long parentId; } |
其中[^\\s\\\\/:\\*\\?\\\"<>\\|\\.]*[^\\s\\\\/:\\*\\?\\\"<>\\|\\.]$為文件名稱校驗的正則表達式,復(fù)制進代碼記得去掉自動生成的\。
到此,對參數(shù)校驗的全部設(shè)置完成。當(dāng)參數(shù)不符合校驗則會拋出異常,接下來就是對拋出的異常進行捕獲:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
@RestControllerAdvice public class BadRequestExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(BadRequestExceptionHandler. class ); @ExceptionHandler (MethodArgumentNotValidException. class ) public ResponseEntity validationBodyException(MethodArgumentNotValidException exception){ BindingResult result = exception.getBindingResult(); if (result.hasErrors()) { List<ObjectError> errors = result.getAllErrors(); errors.forEach(p ->{ FieldError fieldError = (FieldError) p; logger.error( "Data check failure : object{" +fieldError.getObjectName()+ "},field{" +fieldError.getField()+ "},errorMessage{" +fieldError.getDefaultMessage()+ "}" ); }); } return ResponseEntity.ok(getPublicBackValue( false , "目錄名稱不符合標準" )); } public Map<String, Object> getPublicBackValue( boolean flag, String message) { Map<String, Object> map = new HashMap<String, Object>(); if (flag) { map.put( "result_code" , 0 ); } else { map.put( "result_code" , 1 ); } map.put( "result_reason" , message); return map; } } |
@Valid校驗異常捕捉
1
2
3
4
5
|
@Api (tags = { "參數(shù)管理" }) @Validated @RestController @RequestMapping ( "/module/param" ) public class TbModuleParamController {} |
1
2
3
4
5
6
7
8
9
10
|
public ResponseDTO getModuleParam( @PathVariable (name = "moduleId" ) @Valid @NotNull @Max (value = 13 ) @Min (value = 1 ) Integer moduleId) { QueryWrapper<TbModuleParam> paramQueryWrapper = new QueryWrapper<>(); paramQueryWrapper.eq( "module_id" , moduleId).eq( "state" , 1 ); TbModuleParam moduleParam = moduleParamService.getOne(paramQueryWrapper); List<QueryParamVo> queryParamVoList = new ArrayList<>(); if (moduleParam != null ) { queryParamVoList = JSONArray.parseArray(moduleParam.getModuleJson(), QueryParamVo. class ); } return ResponseDTO.defaultResponse(queryParamVoList); } |
1
2
3
4
5
|
@PostMapping (value = "/save" , produces = WebServiceCommonConstant.PRODUCES_JSON) public ResponseDTO<Boolean> addDict( @RequestBody @Validated LandInfoBasicVo saveVo) { boolean result = landInfoService.saveInfo(saveVo); return ResponseDTO.defaultResponse( "保存成功" ); } |
1
2
3
|
@NotBlank (message = "土地名稱不能為空" ) @Size (max = 1 ) private String landName; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
@ControllerAdvice public class ExceptionHandle { private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle. class ); public static List<String> msgList = new ArrayList<>(); /** * 異常處理 * * @param e 異常信息 * @return 返回類是我自定義的接口返回類,參數(shù)是返回碼和返回結(jié)果,異常的返回結(jié)果為空字符串 */ @ExceptionHandler (value = Exception. class ) @ResponseBody public ResponseDTO handle(Exception e) { //自定義異常返回對應(yīng)編碼 if (e instanceof PermissionException) { PermissionException ex = (PermissionException) e; return ResponseDTO.customErrorResponse(ex.getCode(), ex.getMessage()); } //其他異常報對應(yīng)的信息 else { logger.info( "[系統(tǒng)異常]{}" , e.getMessage(), e); msgList.clear(); msgList.add(e.toString()); StackTraceElement[] stackTrace = e.getStackTrace(); for (StackTraceElement element : stackTrace) { msgList.add(element.getClassName() + ":" + element.getMethodName() + "," + element.getLineNumber()); } return ResponseDTO.customErrorResponse(- 1 , "系統(tǒng)內(nèi)部錯誤" ); } } @ExceptionHandler (value = MethodArgumentNotValidException. class ) @ResponseBody public ResponseDTO handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) { List<String> message = new ArrayList<>(); if (ex.getBindingResult() != null ) { for (FieldError item : ex.getBindingResult().getFieldErrors()) { String itemMessage = item.getDefaultMessage(); message.add(itemMessage); } } return ResponseDTO.customErrorResponse(- 1 , message.toString().replace( "[" , "" ).replace( "]" , "" )); } @ExceptionHandler (value = ConstraintViolationException. class ) @ResponseBody public ResponseDTO handleConstraintViolationException(ConstraintViolationException ex) { List<String> message = new ArrayList<>(); Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations(); if (!CollectionUtils.isEmpty(constraintViolations)) { constraintViolations.forEach(v -> message.add(v.getMessage())); } return ResponseDTO.customErrorResponse(- 1 , message.toString().replace( "[" , "" ).replace( "]" , "" )); } } |
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://allyixi.blog.csdn.net/article/details/100706810