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.


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:
Find out a customer with data:
Spring RestControllerAdvice - normal request

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


By grokonez | February 18, 2017.

Last updated on June 4, 2017.

Related Posts

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

  1. Thanks for this article.

    You could add a part about specifying an HTTP status response code by annotating the method handleNotFoundException with @ResponseStatus(HttpStatus.NOT_FOUND).

  2. How to handle AccessDeniedException when thrown in a filter? I guess I can’t use the RestControllerAdvice.

Got Something To Say:

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