From 1698231d4b19934d12ee6326ffe3413f2ac9d6b3 Mon Sep 17 00:00:00 2001 From: Anindita Date: Thu, 14 Dec 2023 01:55:52 -0800 Subject: [PATCH] added AuthorNotFoundException --- .../com/swiz/bcs/controller/GlobalControllerAdvice.java | 5 +++++ .../com/swiz/bcs/exception/AuthorNotFoundException.java | 8 ++++++++ src/main/java/com/swiz/bcs/service/AuthorService.java | 4 +++- 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/swiz/bcs/exception/AuthorNotFoundException.java diff --git a/src/main/java/com/swiz/bcs/controller/GlobalControllerAdvice.java b/src/main/java/com/swiz/bcs/controller/GlobalControllerAdvice.java index c9fa799..36db7d0 100644 --- a/src/main/java/com/swiz/bcs/controller/GlobalControllerAdvice.java +++ b/src/main/java/com/swiz/bcs/controller/GlobalControllerAdvice.java @@ -1,5 +1,6 @@ package com.swiz.bcs.controller; +import com.swiz.bcs.exception.AuthorNotFoundException; import com.swiz.bcs.exception.BookNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -13,5 +14,9 @@ public class GlobalControllerAdvice { public ResponseEntity handleBookNotFoundException(BookNotFoundException e){ return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND); } + @ExceptionHandler(AuthorNotFoundException.class) + public ResponseEntity handleAuthorNotFoundException(AuthorNotFoundException e){ + return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND); + } } diff --git a/src/main/java/com/swiz/bcs/exception/AuthorNotFoundException.java b/src/main/java/com/swiz/bcs/exception/AuthorNotFoundException.java new file mode 100644 index 0000000..41a2bcb --- /dev/null +++ b/src/main/java/com/swiz/bcs/exception/AuthorNotFoundException.java @@ -0,0 +1,8 @@ +package com.swiz.bcs.exception; + +public class AuthorNotFoundException extends RuntimeException{ + public AuthorNotFoundException(String message){ + super(message); + } + } + diff --git a/src/main/java/com/swiz/bcs/service/AuthorService.java b/src/main/java/com/swiz/bcs/service/AuthorService.java index 59966dd..f73564c 100644 --- a/src/main/java/com/swiz/bcs/service/AuthorService.java +++ b/src/main/java/com/swiz/bcs/service/AuthorService.java @@ -3,6 +3,7 @@ import com.swiz.bcs.dto.AuthorDTO; import com.swiz.bcs.entity.Author; +import com.swiz.bcs.exception.AuthorNotFoundException; import com.swiz.bcs.repository.AuthorRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -28,7 +29,8 @@ public List findAllAuthors() { } public Author findAuthorById(Long id) { - return authorRepository.findById(id).orElse(null); + return authorRepository.findById(id) + .orElseThrow(() -> new AuthorNotFoundException("Author not found with ID: "+id)); } // Other author-related operations