I am trying to use bean validation in Webflux. This is what I have so far:
@PostMapping(\"contact\")
fun create(@RequestBody @Valid contact: Mono)
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.
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)
}
. . .
}
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