How to use @RestControllerAdvice for handling Exception with RestfulApi – New Features of Spring Framework 4.3

We had discussed about @ExceptionHandler, @ResponseStatus, @ControllerAdvice in How to use Spring Exception Handler for SpringMVC: @ExceptionHandler, @ResponseStatus, @ControllerAdvice. In the tutorial, JavaSampleApproach will guide to how to use a new feature of Spring Framework 4.3: @RestControllerAdvice.

I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.1.RELEASE

II. @RestControllerAdvice

@RestControllerAdvice is a new feature of Spring Framework 4.3, an annotation with combined @ControllerAdvice + @ResponseBody. So @RestControllerAdvice can help us to handle Exception with RestfulApi by a cross-cutting concern solution: @ExceptionHandler.

Example:

The handleNotFoundException method will handle all exceptions has type: CustomNotFoundException from any @RequestMapping like:

III. Practices
1. Create SpringBoot project

Create a SpringBoot project, add web dependency:

2. Create simple models

Create a simple Customer model:

Create a ResponseMsg model:

3. Create customized exception

4. Create simple Service

5. Create a RestControllerAdvice

6. Create a web controller

7. Run & Check Result

Build & Run the project with SpringBoot App mode. Make requests:
http://localhost:8080/customer/Jack
Find out a customer with data:
Spring RestControllerAdvice - normal request

http://localhost:8080/customer/test
Not Found a customer with name: test, a return is handled by handleNotFoundException(CustomNotFoundException ex), then result is a ResponseMsg model.
Spring RestControllerAdvice - exception request

IV. Sourcecode

SpringRestControllerAdvice


Related Posts


2 thoughts on “How to use @RestControllerAdvice for handling Exception with RestfulApi – New Features of Spring Framework 4.3”

Got Something To Say:

Your email address will not be published. Required fields are marked *

*