Skip to main content


Showing posts from January 6, 2018

REST tutorial : validations


Our API is all good but it currently accepts empty Todos. Let's fix that with validations.

You can find the complete source code here Todoapp
Hibernate Validator Hibernate Validator allows to express and validate application constraints.
Implements JSR 380 bean validation api.
Hibernate validator is entirely separate from the persistence aspects of Hibernate.

Hibernate Validator 6.0 is the Reference Implementation of the Bean Validation 2.0 specification.
Steps:Update gradle compile('javax.validation:validation-api:2.0.1.Final')
compile('org.hibernate:hibernate-validator:6.0.7.Final') Update controller method to add @Valid checkUpdate TodoDto with validatorsCatch validation exception in global exception handler (MethodArgumentNotValidException) Useful annotations @Length(min=, max=) - check if the string length match the range
@Max(value=) - check if the value is less than or equals to max
@Min(value=) - check if the value …

REST tutorial : error handling


So far we have neglected error scenarios in our API. Any application without proper error handling is a disaster.

You can find the complete source code here Todoapp

Try these URLs and see the output.

Spring has handled errors for us!! but the messages are not interesting enough.

Global exception handlingWith Spring's @ControllerAdvice we can handle exception globally. ResponseEntityExceptionHandler : A convenient base class for @ControllerAdvice classes that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods. @RestControllerAdvice is a new feature of Spring Framework 4.3, an annotation with combined @ControllerAdvice + @ResponseBodyEnable spring.mvc.throw-exception-if-no-handler-found to customize 404 error
Note that our TodoService is also updated to throw a custom exception.
See the complete code in error-handling branch.

In next part of the …