It seems I cannot get my @ControllerAdvice to work with Kotlin POJOs. Note, it works when I throw an exception and with path params but doesn't work when validating the body of a request.
ControllerAdvice
@ControllerAdvice
class ExceptionAdvice : ResponseEntityExceptionHandler() {
companion object {
private val log = LoggerFactory.getLogger(this::class.java.name)
}
@ResponseBody
@ExceptionHandler(CustomException::class)
fun onException(exception: CustomException): ResponseEntity<CustomError> {
log.error(Generic.EXCEPTION_PROVIDER_LOG, exception.message, exception.errorType, exception.errorType.httpStatus)
return ResponseEntity(
CustomError(exception.errorType.error, exception.errorType.name), exception.errorType.httpStatus
)
}
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException::class)
fun onValidationFail(exception: ConstraintViolationException): CustomError {
log.error("Request did not conform to spec. Constraints violated: {}", exception.toString())
return CustomError(ErrorType.G001.error, ErrorType.G001.name)
}
}
Controller
@RestController
@RequestMapping(produces = ["application/json; charset=UTF-8"])
@Validated
class StoreDataController {
companion object {
private val log = LoggerFactory.getLogger(this::class.java.name)
}
@Autowired
private lateinit var service: Service
@PostMapping("/store-data")
@Throws(CustomException::class)
fun storeData(@Valid @RequestBody data: Data): ResponseEntity<String> {
return ResponseEntity.ok(data.title)
}
}
Body
data class Data(
@field:Pattern(regexp = "[\\w\\d ]+", message = "Title can only use letters, numbers and spaces") var title: String
)
What Gets Returned
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Invalid request content.",
"instance": "/api/v1/store-data"
}
What should happen is the ControllerAdvice should intercept the error using the @ExceptionHandler(ConstraintViolationException::class) annotation. Do I need to do anything else here?