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)

相关推荐

  • Tcp协议的连接

    技术Tcp协议的连接 Tcp协议的连接Tcp协议是面向连接的协议,因为它具有握手过程
    Tcp连接是成对出现的,是点对点的三次握手客户端和服务器端通信的时候,主要发生下面三个过程
    1.客户端给服务器发送一

    礼包 2021年11月27日
  • 血瘀是什么原因造成的,气虚血瘀能引发高血压吗

    技术血瘀是什么原因造成的,气虚血瘀能引发高血压吗我是从事公共卫生的医生血瘀是什么原因造成的,我来分享一下我的观点。关注中医的朋友对气虚血瘀这个词应该比较熟悉,它在女性和老年群体中较为常见,主要有乏力、气短、精神萎靡等表现

    生活 2021年10月24日
  • debug D命令如何查看指定范围内的内容

    技术debug D命令如何查看指定范围内的内容今天就跟大家聊聊有关debug D命令如何查看指定范围内的内容,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。    

    攻略 2021年11月11日
  • HBase中数据分布模型是怎么样的

    技术HBase中数据分布模型是怎么样的这篇文章主要为大家展示了“HBase中数据分布模型是怎么样的”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“HBase中数据分布模型是怎么

    攻略 2021年12月8日
  • vue中如何实现后台进程定时爬取头条文章

    技术vue中如何实现后台进程定时爬取头条文章这篇文章将为大家详细讲解有关vue中如何实现后台进程定时爬取头条文章,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

    攻略 2021年11月24日
  • 如何翻译和解释ethereum web3.js文档

    技术如何进行以太坊web3.js文档翻译及说明今天就跟大家聊聊有关如何进行以太坊web3.js文档翻译及说明,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。web3

    攻略 2021年12月14日