如何通过@RestControllerAdvice处理@Valid MethodArgumentNotValidException

时间:2018-12-15 11:25:09

标签: java spring rest

你好,
我的测试控制器出现问题,引发了MethodArgumentNotValidException。

我有带有验证注释的实体。

cat output1.txt
AHISISANEXAMPLEOFANINPUTFILEWITHALONGSTRINGOFTEXT
cat output2.txt
TBISISANEXAMPLEOFANINPUTFILEWITHALONGSTRINGOFTEXT
cat output3.txt
THXSISANEXAMPLEOFANINPUTFILEWITHALONGSTRINGOFTEXT

带有@Valid注释的@RequestBody控制器

awk '
FNR==NR{                                                       ##Condition FNR==NR will be TRUE when first file named input.txt is being read.
   a[++count]=$0                                               ##Creating an array named a whose index is increasing value of count and value is current line.
   next                                                        ##next will skip all further statements from here.
}
FNR>1{                                                         ##This condition will be executed when 2nd Input_file textpos.txt is being read(excluding its header).
   close(file)                                                 ##Closing file named file whose value will be output file names, getting created further.
   file="output"(FNR-1)".txt"                                  ##Creating output file named output FNR-1(line number -1) and .txt in it.
   for(i=1;i<=count;i++){                                      ##Starting a for loop from 1 to till count value.
      if($1==1){                                               ##Checking condition if value of 1st field is 1 then do following.
         print $2 substr(a[i],2) > file                        ##Printing $2 substring of value of a[i] which starts from 2nd position till end of line to output file.
      }
      else{
         print substr(a[i],1,$1-1) $2 substr(a[i],$1+1) > file ##Printing substrings 1st 1 to till value of $1-1 $2 and then substring from $1+1 till end of line.
      }
   }
}'  input.txt  textpos.txt                                     ##Mentioning Input_file names here.

现在我要使用单元测试来测试该主控器

public class Tag extends ResourceSupport {
...
    @NotEmpty(message = "Tag name cannot be empty.")
    @NotNull(message = "Tag name cannot be empty.")
    private String name;
}

以这种方式创建全局异常处理类。它仅作为Internet的示例。

@RestController
@RequestMapping(value="/api/tags")
public class TagController {
    .......

    @PostMapping(value = "")
    public ResponseEntity<Tag> addNewTag(@Valid @RequestBody Tag tag) {
        Tag createdTag = tagService.saveOrUpdate(tag);
        return new ResponseEntity<>(createdTag, HttpStatus.CREATED);
    }

}

测试通过了,因为它只是测试状态,但是在控制台中我具有错误日志的堆栈跟踪

  

org.springframework.web.bind.MethodArgumentNotValidException:方法中索引0处的参数的验证失败:.....默认消息[标记名不能为空。]]

这是否正确,错误堆栈跟踪出现在控制台日志中?

1 个答案:

答案 0 :(得分:0)

您的实施效果很好, 这是正常现象,在测试过程中,MockMvc使用

打印MvcResult详细信息
  

PrintingResultHandler

因此它还将通过调用 printResolvedException()

打印通过HandlerExceptionResolver解决的异常

签出PrintingResultHandler

相关问题