course = courseRepository.findById(id);
- * return course.ifPresent() ? course.get() : null;
- * or
- * return course.orElse(null);
+ /*
+ * Using orElseThrow to throw unchecked exception
*/
- return courseRepository.findById(id).orElse(null);
+ return courseRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(id));
}
public void addCourse(Course course) {
@@ -52,12 +45,14 @@ public void addCourse(Course course) {
courseRepository.save(course);
}
- public void updateCourse(Course course) {
- courseRepository.save(course);
+ public void updateCourse(Course course, String id) {
+ if (Objects.nonNull(getCourse(id)))
+ courseRepository.save(course);
}
public void deleteCourse(String id) {
- courseRepository.deleteById(id);
+ if (Objects.nonNull(getCourse(id)))
+ courseRepository.deleteById(id);
}
}
diff --git a/src/main/java/in/hp/java/boot/exceptions/CustomExceptionHandler.java b/src/main/java/in/hp/java/boot/exceptions/CustomExceptionHandler.java
new file mode 100644
index 0000000..3a9edea
--- /dev/null
+++ b/src/main/java/in/hp/java/boot/exceptions/CustomExceptionHandler.java
@@ -0,0 +1,80 @@
+package in.hp.java.boot.exceptions;
+
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.context.request.WebRequest;
+import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
+
+import java.util.Date;
+
+/**
+ * Custom Exception Handler
+ * Used to impose org level exception standard
+ *
+ * @RestController - this acts as a controller as it directly sends response
+ * @ControllerAdvice
+ * - the methods in the class should be common to all controllers,
+ * - hence aop kind of advice is used
+ *
+ * Any exceptions returned from any controller comes to this handler
+ * The method is executed based on @ExceptionHandler advice
+ */
+@RestController
+@ControllerAdvice
+public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
+
+ /**
+ * The below method is used to handle all the exceptions reported by controller
+ * It returns back custom exception with status code 500
+ *
+ * request.getDescription(false) - here false is passed to not reveal client info
+ *
+ * @param ex
+ * @param request
+ * @return
+ */
+ @ExceptionHandler(Exception.class)
+ public final ResponseEntity