@RestControllerAdvice Example SpringBoot

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.loizenjava.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.loizenjava.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.loizenjava.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.loizenjava.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.loizenjava.restcontrolleradvice.advice;
 
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
 
import com.loizenjava.restcontrolleradvice.exception.CustomNotFoundException;
import com.loizenjava.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.loizenjava.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.loizenjava.restcontrolleradvice.exception.CustomNotFoundException;
import com.loizenjava.restcontrolleradvice.model.Customer;
import com.loizenjava.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

Spring @RestControllerAdvice Normal Request
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 Normal Request
Spring @RestControllerAdvice Normal Request

Read More

Sourcecode – @RestControllerAdvice Example SpringBoot

rest-controller-advice-spring-boot

– Github Sourcecode:

rest-controller-advice-spring-boot

How to Implement Push Notification in Spring Boot

Tutorial: “How to Implement Push Notification in Spring Boot – Firebase Cloud Messaging”

In the article Firebase Cloud Messaging – How to Subscribe TOPIC & Receive Messages | Android, we have created an Android App that can subscribe/unsubscribe specific TOPIC and receive Message Data, but we used Firebase Notification Console GUI to generate Notification. Today, we’re gonna look at way to create a Spring Boot Application Server that can make message and push notification to Android Client via Firebase.

Related Post: Firebase Cloud Messaging – XMPP Server example to receive Upstream Messages | Spring Integration

Continue reading “How to Implement Push Notification in Spring Boot”

Spring Boot FCM Push Notification Android Example

Tutorial: “Spring Boot FCM Push Notification Android Example – Firebase Cloud Messaging”

In the article Firebase Cloud Messaging – How to Subscribe TOPIC & Receive Messages | Android, we have created an Android App that can subscribe/unsubscribe specific TOPIC and receive Message Data, but we used Firebase Notification Console GUI to generate Notification. Today, we’re gonna look at way to create a Spring Boot Application Server that can make message and push notification to Android Client via Firebase.

Related Post: Firebase Cloud Messaging – XMPP Server example to receive Upstream Messages | Spring Integration

Continue reading “Spring Boot FCM Push Notification Android Example”

Spring Boot Thymeleaf Ajax Crud Example

Tutorial: “Spring Boot Thymeleaf Ajax Crud Example – SpringBoot RestAPIs CRUD Application with MySQL Examples – FullStack: Frontend (Bootstrap + Ajax JavaScript) to Backend (SpringBoot + MySQL)”

In the tutorial, I will introduce how to create a Fullstack SpringBoot RestAPIs CRUD Application to MySQL database using Spring WEB MVC framework and Spring JPA for building Backend and using Bootstrap, JQuery Ajax for building frontend client

Related posts:


Continue reading “Spring Boot Thymeleaf Ajax Crud Example”

Import Data from Excel to Mysql using Spring Boot

Tutorial: “Import Data from Excel to Mysql using Spring Boot – SpringBoot Upload/Import and Download/Export Excel files to MySQL”

Creating SpringBoot RestAPIs to upload/import and export/download Excel files to databases: PostgreSQL or MySQL is one of the most common question in the development world. Going through the tutorial post, I explain details “How to read data from Excel Sheet and insert into Database table in Spring Boot RestAPIs with Upload/Download Excel functions” by step to step with coding and give you 100% running source code. What we will do?

– I draw full diagram architecture of SpringBoot Upload Download Excel files service.
– I implements how to Excel File service using poi-ooxml.
– I implement SpringBoot Upload Download files RestApis.
– I use Spring JPA to interact with database MySQL.
– I implement a global exception handling to deal with a big uploading file
– I use Ajax and Bootstrap to develop frontend for uploading and downloading excel files.

Related posts:


Continue reading “Import Data from Excel to Mysql using Spring Boot”