springboot如何传参校验@Valid及对其的异常捕获方式

技术springboot如何传参校验@Valid及对其的异常捕获方式这篇文章将为大家详细讲解有关springboot如何传参校验@Valid及对其的异常捕获方式,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读

本文将详细解释回弹如何通过参数来验证@Valid,以及如何捕获它的异常。文章内容质量很高,我就分享给大家作为参考。希望大家看完这篇文章后对相关知识有一定的了解。

传参校验@Valid及对其的异常捕获

回弹参数经常需要验证。例如,创建文件时,需要验证文件名。

本文创建了一个文件夹作为参数验证的示例:

第一步是在要验证的参数类前面添加一个注释@Valid。

@ApiOperation(value='创建目录',notes='在目录下创建新文件夹')。

@ ApiResponsions({ 0

@ apiresponse(代码=500,响应=restcodemsg.class,消息=' error ')。

})

@PostMapping(值='api/scene/createdir ')

public responseentitymapcreateneworeditfile(@ request body @ valixiviewpoixvevo){ 0

.

//验证与内容无关。

}其次,检查并设置参数类:

@数据

@ ApiModel

@Getter

@Setter

@NoArgsConstructor

publicclassixviewVo {

@ApiModelProperty('文件夹与否')

privatebooleandir

@NotBlank(消息='目录名不能为空')。

@pattern(regexp='[^\\s\\\\/:\\*\\?\\\'\\|\\.]*[^\\s\\\\/:\\*\\?\\\'\\|\\.]$ ',消息='目录名不符合标准')。

@ApiModelProperty('目录名')

privateStringdirname

@ApiModelProperty('父目录标识')

privateLongparentId

}其中[\ \ s \ \ \/: \ \ * \ \?\\\'\\|\\.]*[^\\s\\\\/:\\*\\?\ \ \' \ \ | \ \.] $是用于文件名验证的正则表达式。请记住删除自动生成的\。

此时,参数验证的所有设置都已完成。当参数不符合验证时,将引发异常。下一步是捕获抛出的异常:

@RestControllerAdvice

public class BadRequestExceptionHandler {

privatesticfinallogger=logger factory . getlogger(BadRequestExceptionHandler . class);

@ exception handler(method argumentnotvalidexception . class)

public responseentityvalidationbodyexception(method argumentnot

ValidException 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 = {"参数管理"})
@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 返回类是我自定义的接口返回类,参数是返回码和返回结果,异常的返回结果为空字符串
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseDTO handle(Exception e) {
        //自定义异常返回对应编码
        if (e instanceof PermissionException) {
            PermissionException ex = (PermissionException) e;
            return ResponseDTO.customErrorResponse(ex.getCode(), ex.getMessage());
        }
        //其他异常报对应的信息
        else {
            logger.info("[系统异常]{}", 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, "系统内部错误");
        } 
    }
 
    @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("]",""));
    }
}

关于springboot如何传参校验@Valid及对其的异常捕获方式就分享到这里了,希望

内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/37094.html

(0)

相关推荐

  • 抖音赞在哪买,哪里抖音刷赞最安全?

    技术抖音赞在哪买,哪里抖音刷赞最安全?抖音应该是最近比较火的软件了,对此,大家都不陌生吧,很多的用户发个视频就好几十万的赞,其实都是可以刷的!要想上精选有必要要有播放量等等一系列数据,这个数据很的重要,没有数据就没有展现

    测评 2021年10月20日
  • 怎么用Python爬虫预测今年双十一销售额

    技术怎么用Python爬虫预测今年双十一销售额本篇内容主要讲解“怎么用Python爬虫预测今年双十一销售额”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用Python爬虫

    攻略 2021年11月10日
  • 六允读什么,允字上部是什么字,读音是什么

    技术六允读什么,允字上部是什么字,读音是什么“允”字的拼音是yǔn六允读什么。
    1、允的解释:一是答应,认可;二是公平得当;三是信,实;四是宽容,理解;五是包容;六是大、极致。
    2、组词、解释及造句
    (1)允许(yǔnx

    生活 2021年10月25日
  • 抖音播放量突然被限流降权是什么原因

    技术抖音播放量突然被限流降权是什么原因 抖音播放量突然被限流降权是什么原因抖音播放量突然被限流降权是什么原因本来发布的视频播放量都挺稳定的,但突然有一天发布的视频播放量急降,这个情况相信不少用户也遇到过

    礼包 2021年11月27日
  • 生成器与常见内置函数

    技术生成器与常见内置函数 生成器与常见内置函数异常捕获补充
    # 异常捕获的完整形式
    try:name
    except NameError as e:pass
    except Exception as e:p

    礼包 2021年11月23日
  • 怎么使用Python爬虫

    技术怎么使用Python爬虫本篇内容介绍了“怎么使用Python爬虫”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!1.导

    攻略 2021年10月29日