Spring REST Exception Handling Example - ControllerAdvice

In this article, we will learn how to handle errors in Spring Boot REST application.

Technologies used :

  • Spring Boot 2.1.1.RELEASE
  • Spring 5.1.3.RELEASE
  • Maven 3
  • Java 8
Since Spring 3.2 brings support for an ecumenical @ExceptionHandler with the @ControllerAdvice annotation.
This enables a mechanism that breaks away from the older MVC model and makes utilization of ResponseEntity along with the type safety and flexibility of @ExceptionHandler.

Project Structure


pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf.exception.demo</groupId>
<artifactId>knfExceptionHandlingDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>knfExceptionHandlingDemo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

DemoController

package com.example.demo.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.exception.CustomerNotFoundException;

@RestController
public class DemoController {
@GetMapping(path = "/customer/{id}")
public @ResponseBody ResponseEntity<String> getCustomerId
                           (@PathVariable String id) {
if (id.equals("17")) {
throw new CustomerNotFoundException();
}
return new ResponseEntity<String>("Success", HttpStatus.ACCEPTED);
}
}

CustomerNotFoundException

package com.example.demo.exception;

public class CustomerNotFoundException extends RuntimeException {

private static final long serialVersionUID = 1L;

public CustomerNotFoundException() {
super("Customer Not Found");
}
}

CustomErrorResponse

package com.example.demo.exception.response;

import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDateTime;

public class CustomErrorResponse {

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm:ss")
private LocalDateTime timestamp;
private int status;
private String error;
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}

GlobalExceptionHandler

In Spring Boot, we can use @ControllerAdvice to handle custom exceptions.
package com.example.demo.exceptionhandler;

import java.time.LocalDateTime;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import com.example.demo.exception.CustomerNotFoundException;
import com.example.demo.exception.response.CustomErrorResponse;

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(CustomerNotFoundException.class)
public ResponseEntity<CustomErrorResponse> globalExceptionHandler
                   (Exception ex, WebRequest request) {
CustomErrorResponse errors = new CustomErrorResponse();
errors.setTimestamp(LocalDateTime.now());
errors.setError(ex.getMessage());
errors.setStatus(HttpStatus.NOT_FOUND.value());
return new ResponseEntity<>(errors, HttpStatus.NOT_FOUND);
}
}

Main class

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

Run

$ mvn spring-boot:run

Test endpoint using postman

Case 1: Success(No Exception)



Case 2: Exception(Custom error response)




More related topics,

Java - Angular - VueJS - ReactJS

NodeJS - Angular - VueJS - ReactJS

Python - Flask  - Angular - VueJS - ReactJS

Comments

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

ReactJS - Bootstrap - Buttons

Spring Core | BeanFactoryPostProcessor | Example

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Custom Exception Handling in Quarkus REST API

ReactJS, Spring Boot JWT Authentication Example

Java, Spring Boot Mini Project - Library Management System - Download

Top 5 Java ORM tools - 2024

Java - DES Encryption and Decryption example