Spring webflux bean validation not working

后端 未结 3 1601
南笙
南笙 2021-02-15 17:56

I am trying to use bean validation in Webflux. This is what I have so far:

@PostMapping(\"contact\")
fun create(@RequestBody @Valid contact: Mono)         


        
3条回答
  •  猫巷女王i
    2021-02-15 18:40

    I had to combine few of the answers from SO to get the validation correct. What I did was:

    • Made my data class as suggested here.

      • Then i used javax.validation.Validator class to validate the data class.

    import javax.validation.Validator import javax.validation.ConstraintViolationException

    @Service
    open class MyService {
        @Autowired
        lateinit var repository: UserRepository
    
        @Autowired
        lateinit var validator: Validator
    
         open fun createUser(user: User): Mono {
             val violations = validator.validate(user)
              //if it violates our constraints, it will throw an exception, which we 
              //handle using global exception handler
              if(violations.isNotEmpty()){
                   throw ConstraintViolationException(violations)
               }
               return repo.save(user)
             }
    . . .
    }
    
    • Add these lines in application.properties.
    spring.mvc.throw-exception-if-no-handler-found=true
    spring.resources.add-mappings=false
    

    And to catch the exceptions.

    @RestControllerAdvice    
    open class ExceptionHandlers {
    
      @ExceptionHandler(ConstraintViolationException::class)
      @ResponseStatus(HttpStatus.BAD_REQUEST)
      fun throwConstraintViolationExcetion(ex: ConstraintViolationException): ApiResponse {
        return ApiResponse (message= ex.message.toString(), data= null);
      }
    }
    

    p.s ApiResponse is just a data class that takes server message & data as parameters. No need to handle errors in @Controller as it will be thrown by the @Service class

提交回复
热议问题