@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.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

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

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”

Upload and Read CSV File in Spring Boot

Tutorial: “Upload and Read CSV File in Spring Boot – SpringBoot Upload Download Multiple CSV files to MySQL/PostgreSQL with Ajax”

Creating SpringBoot RestAPIs to upload and download multiple CSV files to databases: MySQL and PostgreSQL is one of the most common question in the development world. Going through the tutorial post”SpringBoot Upload Download Multiple CSV files to MySQL/PostgreSQL”, I explain details how to do it by step to step with coding and give you 100% running source code. What we will do?

– I draw an overview diagram architecture of SpringBoot RestAPI Upload CSV Files.
– I use Spring Web to development Spring RestApis.
– I use ApacheCommon or Open CSV libraries to parse and read CSV files.
– I use SpringJPA to save data from CSV files to MySQL and PostgreSQL.
– I implement a SpringBoot Global Exception Handler when uploading with a very big files and fail.
– I use Ajax and Bootstrap to implement a frontend client to upload/download CSV files.

Related posts:


Continue reading “Upload and Read CSV File in Spring Boot”

Spring Boot Mongodb Angular Crud Example Github

Tutorial: “Spring Boot Mongodb Angular Crud Example Github – using Spring Boot Data & Atlas MongoDB”

In the tutorial, I introduce how to build an “Angular SpringBoot MongoDB CRUD Example RestAPIs” project with the help of SpringData and Atlas MongoDB for POST/GET/PUT/DELETE requests with step by step coding examples:

– SpringBoot project produces CRUD RestAPIs with MongoDB database documents using the supporting of Spring Data.
– Angular project will consume the SpringBoot CRUD RestAPIs then show up on component’s views.

Related posts:


– I draw a fullstack overview Diagram Architecture from Angular Frontend to MongoDB database through SpringBoot RestAPI backend.
– Develop SpringBoot CRUD RestAPIs with the supporting of SpringWeb Framework.
– Implement Angular CRUD application with the Angular Httpclient to do CRUD request (Post/Get/Put/Delete) to SpringBoot Backend APIs.
– I create a testsuite with a number of integrative testcases with CRUD RestAPI requests from Angular HttpClient to do CRUD requests to SpringBoot RestAPIs Server and save/retrieve data to MongoDB database.

Continue reading “Spring Boot Mongodb Angular Crud Example Github”