From 1553ed2e5ac5433599a5f7bd79e04b6518e8cc2e Mon Sep 17 00:00:00 2001 From: dev-swapnildixit Date: Mon, 24 Jun 2024 17:05:45 +0530 Subject: [PATCH] Added exception handler --- .../src/app/services/blog.service.ts | 3 +- .../src/environments/environment.ts | 1 + .../controller/WordPressController.java | 23 +++++++++++-- .../exception/GlobalExceptionHandler.java | 33 +++++++++++++++++++ .../exception/PostNotFoundException.java | 7 ++++ 5 files changed, 63 insertions(+), 4 deletions(-) create mode 100644 blogs-analyzer-ui/src/environments/environment.ts create mode 100644 blogs-analyzer/src/main/java/com/nashtech/blogs/analyzer/exception/GlobalExceptionHandler.java create mode 100644 blogs-analyzer/src/main/java/com/nashtech/blogs/analyzer/exception/PostNotFoundException.java diff --git a/blogs-analyzer-ui/src/app/services/blog.service.ts b/blogs-analyzer-ui/src/app/services/blog.service.ts index 03f85ec..0e856ae 100644 --- a/blogs-analyzer-ui/src/app/services/blog.service.ts +++ b/blogs-analyzer-ui/src/app/services/blog.service.ts @@ -1,12 +1,13 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { map, Observable } from 'rxjs'; +import { environment } from '../../environments/environment'; @Injectable({ providedIn: 'root' }) export class BlogService { - private baseUrl = 'http://localhost:8888/api'; + private baseUrl = environment.apiUrl; constructor(private http: HttpClient) { diff --git a/blogs-analyzer-ui/src/environments/environment.ts b/blogs-analyzer-ui/src/environments/environment.ts new file mode 100644 index 0000000..7c736a5 --- /dev/null +++ b/blogs-analyzer-ui/src/environments/environment.ts @@ -0,0 +1 @@ +export const environment = { production: false, apiUrl: 'http://localhost:8888/api' }; diff --git a/blogs-analyzer/src/main/java/com/nashtech/blogs/analyzer/controller/WordPressController.java b/blogs-analyzer/src/main/java/com/nashtech/blogs/analyzer/controller/WordPressController.java index 6707b61..94165e3 100644 --- a/blogs-analyzer/src/main/java/com/nashtech/blogs/analyzer/controller/WordPressController.java +++ b/blogs-analyzer/src/main/java/com/nashtech/blogs/analyzer/controller/WordPressController.java @@ -1,5 +1,6 @@ package com.nashtech.blogs.analyzer.controller; +import com.nashtech.blogs.analyzer.exception.PostNotFoundException; import com.nashtech.blogs.analyzer.model.Post; import org.json.JSONArray; import org.json.JSONObject; @@ -34,6 +35,9 @@ public class WordPressController { public ResponseEntity getPostById(@PathVariable Long id) { String url = WORDPRESS_API_BASE_URL + "posts/" + id; String response = restTemplate.getForObject(url, String.class); + if (response == null || response.isEmpty()) { + throw new PostNotFoundException("Post with ID " + id + " not found"); + } JSONObject jsonResponse = new JSONObject(response); String content = jsonResponse.getJSONObject("content").getString("rendered"); @@ -46,6 +50,9 @@ public ResponseEntity searchPosts(@RequestParam(value = "search", requir String url = WORDPRESS_API_BASE_URL + "posts?search=" + search; String response = restTemplate.getForObject(url, String.class); JSONArray postsArray = new JSONArray(response); + if (postsArray.isEmpty()) { + throw new PostNotFoundException("No posts found with the search term: " + search); + } StringBuilder renderedContent = new StringBuilder(); for (int i = 0; i < postsArray.length(); i++) { @@ -62,6 +69,9 @@ public ResponseEntity searchPostsByTitle(@RequestParam String title) { String url = WORDPRESS_API_BASE_URL + "posts?search=" + title + "&searchFields=title"; String response = restTemplate.getForObject(url, String.class); JSONArray postsArray = new JSONArray(response); + if (postsArray.isEmpty()) { + throw new PostNotFoundException("No posts found with the title: " + title); + } StringBuilder renderedContent = new StringBuilder(); for (int i = 0; i < postsArray.length(); i++) { @@ -81,6 +91,7 @@ public ResponseEntity getPostsByAuthorId(@RequestParam String authorId) int page = 1; int totalPages = 1; + boolean postFound = false; StringBuilder renderedContent = new StringBuilder(); @@ -94,6 +105,7 @@ public ResponseEntity getPostsByAuthorId(@RequestParam String authorId) } for (int i = 0; i < postsArray.length(); i++) { + postFound = true; JSONObject post = postsArray.getJSONObject(i); String postId = post.get("id").toString(); String title = post.getJSONObject("title").getString("rendered"); @@ -105,7 +117,9 @@ public ResponseEntity getPostsByAuthorId(@RequestParam String authorId) } page++; } - + if (!postFound) { + throw new PostNotFoundException("No posts found for author ID: " + authorId); + } return ResponseEntity.ok(renderedContent.toString()); } @@ -125,9 +139,12 @@ public ResponseEntity> getAllPosts( ); List> postMaps = response.getBody(); + if (postMaps == null || postMaps.isEmpty()) { + throw new PostNotFoundException("No posts found for the given page: " + page); + } List posts = new ArrayList<>(); - if (postMaps != null) { + for (Map postMap : postMaps) { Post post = new Post(); post.setId(((Number) postMap.get("id")).longValue()); @@ -147,7 +164,7 @@ public ResponseEntity> getAllPosts( } fetchAuthorNames(posts); - } + HttpHeaders headers = response.getHeaders(); int totalPosts = Integer.parseInt(Objects.requireNonNull(headers.getFirst("X-WP-Total"))); diff --git a/blogs-analyzer/src/main/java/com/nashtech/blogs/analyzer/exception/GlobalExceptionHandler.java b/blogs-analyzer/src/main/java/com/nashtech/blogs/analyzer/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..af7204d --- /dev/null +++ b/blogs-analyzer/src/main/java/com/nashtech/blogs/analyzer/exception/GlobalExceptionHandler.java @@ -0,0 +1,33 @@ +package com.nashtech.blogs.analyzer.exception; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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 java.io.IOException; + +@ControllerAdvice +public class GlobalExceptionHandler { + private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + @ExceptionHandler(Exception.class) + public ResponseEntity handleGlobalException(Exception ex, WebRequest request) { + logger.error("Exception occurred: {}", ex.getMessage(), ex); + return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(IOException.class) + public ResponseEntity handleIOException(IOException ex, WebRequest request) { + logger.error("IOException occurred: {}", ex.getMessage(), ex); + return new ResponseEntity<>("An I/O error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(PostNotFoundException.class) + public ResponseEntity handlePostNotFoundException(PostNotFoundException ex) { + return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND); + } +} diff --git a/blogs-analyzer/src/main/java/com/nashtech/blogs/analyzer/exception/PostNotFoundException.java b/blogs-analyzer/src/main/java/com/nashtech/blogs/analyzer/exception/PostNotFoundException.java new file mode 100644 index 0000000..06d3c7f --- /dev/null +++ b/blogs-analyzer/src/main/java/com/nashtech/blogs/analyzer/exception/PostNotFoundException.java @@ -0,0 +1,7 @@ +package com.nashtech.blogs.analyzer.exception; + +public class PostNotFoundException extends RuntimeException { + public PostNotFoundException(String message) { + super(message); + } +} \ No newline at end of file