springboot 傳參校驗@Valid及對其的異常捕獲方式
傳參校驗@Valid及對其的異常捕獲
springboot參數(shù)經(jīng)常需要進行校驗,比如創(chuàng)建文件,文件名就需要進行一定的校驗。
本文以創(chuàng)建文件夾為例進行參數(shù)校驗:controller:
首先就是在需要校驗的參數(shù)類前面添加注釋@Valid
@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è)置:
@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\\\\/:\\*\\?\\\"<>\\|\\.]$為文件名稱校驗的正則表達式,復制進代碼記得去掉自動生成的\。
到此,對參數(shù)校驗的全部設(shè)置完成。當參數(shù)不符合校驗則會拋出異常,接下來就是對拋出的異常進行捕獲:
@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校驗異常捕捉
@Api(tags = {"參數(shù)管理"}) @Validated @RestController @RequestMapping("/module/param") public class TbModuleParamController {}
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); }
@PostMapping(value = "/save", produces = WebServiceCommonConstant.PRODUCES_JSON) public ResponseDTO<Boolean> addDict(@RequestBody @Validated LandInfoBasicVo saveVo) { boolean result = landInfoService.saveInfo(saveVo); return ResponseDTO.defaultResponse("保存成功"); }
@NotBlank(message = "土地名稱不能為空") @Size(max = 1) private String landName;
@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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot實現(xiàn)簡單的定時任務(wù)
這篇文章主要給大家介紹了關(guān)于利用Spring Boot實現(xiàn)簡單的定時任務(wù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者使用Spring Boot具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2020-07-07淺談java對象結(jié)構(gòu) 對象頭 Markword
這篇文章主要介紹了淺談java對象結(jié)構(gòu) 對象頭 Markword,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10Java中設(shè)置session超時(失效)的三種方法
這篇文章主要介紹了Java中設(shè)置session超時(失效)的三種方法,本文講解了在web容器中設(shè)置、在工程的web.xml中設(shè)置、通過java代碼設(shè)置3種方法,需要的朋友可以參考下2015-07-07解決SpringBoot內(nèi)嵌Tomcat并發(fā)容量的問題
這篇文章主要介紹了解決SpringBoot內(nèi)嵌Tomcat并發(fā)容量的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06SpringBoot2 實現(xiàn)JPA分頁和排序分頁的案例
這篇文章主要介紹了SpringBoot2 實現(xiàn)JPA分頁和排序分頁的案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01一文詳細springboot實現(xiàn)MySQL數(shù)據(jù)庫的整合步驟
Spring Boot可以很方便地與MySQL數(shù)據(jù)庫進行整合,下面這篇文章主要給大家介紹了關(guān)于springboot實現(xiàn)MySQL數(shù)據(jù)庫的整合步驟,文中通過圖文以及代碼介紹的非常詳細,需要的朋友可以參考下2024-03-03