Commit 8e675647 authored by Suresh Kumar's avatar Suresh Kumar

Global Exception Handling

parent 6c965654
<?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.7.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gloabalexceptionhandling</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>GlobalExceptionHandling</name>
<description>Global Exception Handling in Spring Boot </description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.gloabalexceptionhandling.Controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.gloabalexceptionhandling.Model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import com.gloabalexceptionhandling.Service.StudentServiceImpl;
import java.util.List;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
@RestController
public class StudentController {
@Autowired
private StudentServiceImpl studentService;
@GetMapping("/students")
public List<Student> getAllStudents() {
return this.studentService.getAllStudents();
}
@GetMapping("/students/{id}")
public ResponseEntity<?> getStudentByID(@PathVariable("id") int id) {
Student getStudent = studentService.getStudentByID(id);
return new ResponseEntity<Student>(getStudent, OK);
}
@PostMapping("/students")
public ResponseEntity<?> addStudent(@RequestBody Student student) {
Student st = this.studentService.addStudent(student);
return new ResponseEntity<Student>(st, CREATED);
}
@PutMapping("/students/{studentId}")
public Student updateStudent(@RequestBody Student student, @PathVariable("studentId")int studentId) {
this.studentService.updateStudent(student, studentId);
return student;
}
@DeleteMapping("/students/{studentId}")
public void deleteStudent(@PathVariable("studentId") int studentId) {
this.studentService.deleteStudentById(studentId);
}
}
\ No newline at end of file
package com.gloabalexceptionhandling.Exception;
import lombok.*;
@Getter
@Setter
@ToString
@NoArgsConstructor@AllArgsConstructor
public class ArrayResponseDto {
private String date;
private String errorMessage;
}
package com.gloabalexceptionhandling.Exception;
import org.springframework.stereotype.Component;
@Component
public class EmptyInputException extends RuntimeException {
private String errorCode;
private String errorMessage;
private static final long serialVersionUID = 1L;
public String getErrorCode(){
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public EmptyInputException(String errorCode, String errorMessage){
super();
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public EmptyInputException(){
}
}
package com.gloabalexceptionhandling.Exception;
public class NoSuchElementException extends RuntimeException{
private String errorCode;
private String errorMessage;
private static final long serialVersionUID = 1L;
public String getErrorCode(){
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public NoSuchElementException(String errorCode, String errorMessage){
super();
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public NoSuchElementException(){
}
}
package com.gloabalexceptionhandling;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GlobalExceptionHandlingApplication {
public static void main(String[] args) {
SpringApplication.run(GlobalExceptionHandlingApplication.class, args);
System.out.println("Project Started..............");
}
}
package com.gloabalexceptionhandling.Handler;
import java.util.NoSuchElementException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.gloabalexceptionhandling.Exception.ArrayResponseDto;
import com.gloabalexceptionhandling.Exception.EmptyInputException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice extends ResponseEntityExceptionHandler {
@ExceptionHandler(EmptyInputException.class)
public ResponseEntity<String> handleEmptyInput(EmptyInputException emptyInputException){
return new ResponseEntity("Sorry Your Fields Are Empty Please Check Fields ...........!! " , HttpStatus.BAD_REQUEST);
}
@ExceptionHandler (NullPointerException.class)
public ResponseEntity<?> handleNullPointerException(NullPointerException nullPointerException){
ArrayResponseDto arrayResponseDto = new ArrayResponseDto("02/08/2022", "There Is No Student Available Belongs to This ID");
return new ResponseEntity(arrayResponseDto, HttpStatus.OK);
}
@ExceptionHandler (NoSuchElementException.class)
public ResponseEntity<String> handleNoSuchElementException(NoSuchElementException noSuchElementException){
return new ResponseEntity<String>("There Is No Value Present For This Id ", HttpStatus.NOT_FOUND);
}
}
package com.gloabalexceptionhandling.Model;
import lombok.*;
import javax.persistence.*;
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "studentHandling")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String degree;
private String university;
}
package com.gloabalexceptionhandling.Repository;
import com.gloabalexceptionhandling.Model.Student;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentRepository extends CrudRepository<Student, Integer> {
Student findById(int id);
}
package com.gloabalexceptionhandling.Service;
import java.util.List;
import com.gloabalexceptionhandling.Model.Student;
public interface StudentService {
//Get All Students
public List<Student> getAllStudents();
// Students get by id
public Student getStudentByID(int id);
// Add student records
public Student addStudent(Student st);
//Delete by id
void deleteStudentById(int sid);
// Update records
public void updateStudent(Student sstudent, int studentId);
}
package com.gloabalexceptionhandling.Service;
import java.util.List;
import java.util.NoSuchElementException;
import org.springframework.stereotype.Service;
import com.gloabalexceptionhandling.Model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import com.gloabalexceptionhandling.Repository.StudentRepository;
import com.gloabalexceptionhandling.Exception.EmptyInputException;
@Service
public class StudentServiceImpl implements StudentService{
@Autowired
private StudentRepository studentRepository;
@Override
public List<Student> getAllStudents() {
List<Student> list = (List<Student>) studentRepository.findAll();
if (list.isEmpty())
throw new EmptyInputException("604", "Hey List is Completely Empty ......!!");
return list;
}
@Override
public Student getStudentByID(int id) {
Student student= studentRepository.findById(id);
if (student.getName().length()==0)
throw new NoSuchElementException("There Is No Student Available for this id ");
return student;
}
@Override
public Student addStudent(Student st) {
if (st.getName().isEmpty() || st.getName().length()==0){
throw new EmptyInputException("601", "Input Field Are Empty....!!");
}
Student savestudent = studentRepository.save(st);
return savestudent;
}
@Override
public void deleteStudentById(int sid) {
studentRepository.deleteById(sid);
}
@Override
public void updateStudent(Student student, int studentId) {
student.setId(studentId);
studentRepository.save(student);
}
}
\ No newline at end of file
server.port=8081
spring.datasource.name=firstDBPractice
spring.datasource.url=jdbc:mysql://localhost:3306/firstDBPractice?characterEncoding=utf8
spring.datasource.username= root
spring.datasource.password=nisum123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL55Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
package com.gloabalexceptionhandling;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class GlobalExceptionHandlingApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment