Tutorial: “@RestControllerAdvice Example SpringBoot – Error Handling for REST with Spring”.
In the article, I introduce about @RestControllerAdvice annotation of SpringBoot to handle RestAPI exception with a Github running sourcecode and details explanation example steps.
* Technologies we use in the article:
– Java 1.8
– Maven
– Spring Boot
Annotation Type @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.
@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@ControllerAdvice
@ResponseBody
public @interface RestControllerAdvice
@RestControllerAdvice is processed if an appropriate HandlerMapping-HandlerAdapter pair is configured such as the RequestMappingHandlerMapping-RequestMappingHandlerAdapter pair which are the default in the MVC Java config and the MVC namespace.
Example:
@RestControllerAdvice
public class WebRestControllerAdvice {
@ExceptionHandler(CustomNotFoundException.class)
public ResponseMsg handleNotFoundException(CustomNotFoundException ex) {
ResponseMsg responseMsg = new ResponseMsg(ex.getMessage());
return responseMsg;
}
}
The handleNotFoundException method will handle all exceptions has type: CustomNotFoundException from any @RequestMapping like:
@RequestMapping(value="/customer/{name}")
public Customer findCustomerByName(@PathVariable("name")String name){
Customer cust = customerService.findCustomerByName(name);
if(null == cust){
throw new CustomNotFoundException("Not found customer with name is " + name);
}
return cust;
}
Create SpringBoot Project – @RestControllerAdvice Example
We use SpringToolSuite to create a SpringBoot project with below dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
SpringBoot Create a Java Model Data
Create a Customer model with as below code:
package com.loizenai.restcontrolleradvice.model;
public class Customer {
private String name;
private int age;
public Customer(String name, int age){
this.setName(name);
this.setAge(age);
}
// name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// age
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
In the tutorial “@RestControllerAdvice Example with SpringBoot”, we create a ResponseMsg
model:
package com.loizenai.restcontrolleradvice.model;
public class ResponseMsg {
private String message;
public ResponseMsg(String msg){
this.message = msg;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Create Customized Exception
In the tutorial “@RestControllerAdvice Example SpringBoot”, we create a customized exception as below:
package com.loizenai.restcontrolleradvice.exception;
public class CustomNotFoundException extends RuntimeException{
public CustomNotFoundException(String msg) {
super(msg);
}
}
Create SpringBoot Service
import java.util.HashMap;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Service;
import com.loizenai.restcontrolleradvice.model.Customer;
@Service
public class CustomerService {
HashMap<String, Customer> custStorage = new HashMap<String, Customer>();
@PostConstruct
void init() {
Customer jack = new Customer("Jack", 20);
Customer peter = new Customer("Peter", 30);
custStorage.put("Jack", jack);
custStorage.put("Peter", peter);
}
public Customer findCustomerByName(String name) {
return custStorage.get(name);
}
}
Implement a SpringBoot @RestControllerAdvice
package com.loizenai.restcontrolleradvice.advice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.loizenai.restcontrolleradvice.exception.CustomNotFoundException;
import com.loizenai.restcontrolleradvice.model.ResponseMsg;
@RestControllerAdvice
public class WebRestControllerAdvice {
@ExceptionHandler(CustomNotFoundException.class)
public ResponseMsg handleNotFoundException(CustomNotFoundException ex) {
ResponseMsg responseMsg = new ResponseMsg(ex.getMessage());
return responseMsg;
}
}
SpringBoot RestAPI Web Controller
Now we create a SpringBoot RestAPIs that will throw an exception when trying to find-out an un-existed items in database:
package com.loizenai.restcontrolleradvice.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.loizenai.restcontrolleradvice.exception.CustomNotFoundException;
import com.loizenai.restcontrolleradvice.model.Customer;
import com.loizenai.restcontrolleradvice.service.CustomerService;
@RestController
public class WebController {
@Autowired
CustomerService customerService;
@RequestMapping(value = "/customer/{name}")
public Customer findCustomerByName(@PathVariable("name") String name) {
Customer cust = customerService.findCustomerByName(name);
if (null == cust) {
throw new CustomNotFoundException("Not found customer with name is " + name);
}
return cust;
}
}
Run & Check Result – @RestControllerAdvice Example SpringBoot
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.

Read More
Sourcecode – @RestControllerAdvice Example SpringBoot
rest-controller-advice-spring-boot
– Github Sourcecode: