Unit-3
Building Restful Microservices
&
Exception Handling
Creating REST APIs
• Refer Ex:2
Exception Handling
• Handling exceptions and errors in APIs and sending the
proper response to the client is good for enterprise
applications
@ExceptionHandler Annotation
• @ExceptionHandler annotation provided by Spring Boot can be used to
handle exceptions in particular Handler classes or Handler methods.
• Example
@ExceptionHandler(IDNotFoundException.class)
public ResponseEntity<String> handleIdExc(IDNotFoundException e)
{
return new ResponseEntity<String>("specific exc: id not
found",HttpStatus.NOT_FOUND);
}
@RestControllerAdvice for Global Exception
Handler
• @ExceptionHandler annotated method can only handle the exceptions
thrown by that particular class.
• To handle any exception thrown throughout the application, can define
a global exception handler class and annotate it with
@ControllerAdvice.
• This annotation helps to integrate multiple exception handlers into a
single global unit.
Contd...
Example - Global Exception Handler
@RestControllerAdvice
public class GlobalException {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleArgExc(IllegalArgumentException e)
{
return new ResponseEntity<String>("global exc: id not
found",HttpStatus.BAD_REQUEST);
}
}
Exception Handling - Example Code
Develop a Spring Boot Restful Webservice that performs CRUD operations
on Customer Entity, using MYSQL database for storing all necessary data.
Step 1: Creating a JPA Entity class Customer with three fields id, name, and address.
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String address;
}
Contd...
Step 2: Creating a CustomerRepository Interface
public interface CustomerRepository
extends JpaRepository<Customer, Long> {
}
Contd...
Step 3: Creating Custom made Exceptions that can be thrown during necessary scenarios while performing
CRUD.
• CustomerAlreadyExistsException: This exception can be thrown when the user tries to add a customer
that already exists in the database.
public class CustomerAlreadyExistsException extends Exception {
private String message;
public CustomerAlreadyExistsException() {}
public CustomerAlreadyExistsException(String msg)
{
super(msg);
this.message = msg;
}
}
Contd...
• NoSuchCustomerExistsException: This exception can be thrown when the user tries to
delete or update a customer record that doesn’t exist in the database.
public class NoSuchCustomerExistsException extends Exception {
private String message;
public NoSuchCustomerExistsException() {}
public NoSuchCustomerExistsException(String msg)
{
super(msg);
this.message = msg;
}
}
Contd...
Step 4: Creating Rest Controller CustomerController
which defines various APIs
@RestController
public class CustomerController {
@Autowired private CustomerRepository custRepo;
// Get Customer by Id
@GetMapping("/getCustomer/{id}")
public Customer getCustomer(@PathVariable("id") Long id)
{
return custRepo.findById(id).orElseThrow( () -> new NoSuchElementException(
"NO CUSTOMER PRESENT WITH ID = " + id));
}
Step 4:Contd...
// Add new Customer
@PostMapping("/addCustomer")
public String addcustomer(@RequestBody Customer customer)
{
Customer existingCustomer = custRepo.findById(customer.getId()).orElse(null);
if (existingCustomer == null) {
custRepo.save(customer);
return "Customer added successfully";
}
else
throw new CustomerAlreadyExistsException("Customer already exists!!");;
}
Step 4:Contd...
// Update Customer details
@PutMapping("/updateCustomer")
public String updateCustomer(@RequestBody Customer customer)
{
Customer existingCustomer= custRepo.findById(customer.getId()).orElse(null);
if (existingCustomer == null)
throw new NoSuchCustomerExistsException("No Such Customer exists!!");
else {
existingCustomer.setName(customer.getName());
existingCustomer.setAddress(customer.getAddress());
custRepo.save(existingCustomer);
return "Record updated Successfully";
}
}