Skip to content

Commit

Permalink
Added exception handler
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-swapnildixit committed Jun 24, 2024
1 parent 81e858e commit 1553ed2
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 4 deletions.
3 changes: 2 additions & 1 deletion blogs-analyzer-ui/src/app/services/blog.service.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down
1 change: 1 addition & 0 deletions blogs-analyzer-ui/src/environments/environment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const environment = { production: false, apiUrl: 'http://localhost:8888/api' };
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -34,6 +35,9 @@ public class WordPressController {
public ResponseEntity<String> 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");
Expand All @@ -46,6 +50,9 @@ public ResponseEntity<String> 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++) {
Expand All @@ -62,6 +69,9 @@ public ResponseEntity<String> 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++) {
Expand All @@ -81,6 +91,7 @@ public ResponseEntity<String> getPostsByAuthorId(@RequestParam String authorId)

int page = 1;
int totalPages = 1;
boolean postFound = false;

StringBuilder renderedContent = new StringBuilder();

Expand All @@ -94,6 +105,7 @@ public ResponseEntity<String> 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");
Expand All @@ -105,7 +117,9 @@ public ResponseEntity<String> getPostsByAuthorId(@RequestParam String authorId)
}
page++;
}

if (!postFound) {
throw new PostNotFoundException("No posts found for author ID: " + authorId);
}
return ResponseEntity.ok(renderedContent.toString());
}

Expand All @@ -125,9 +139,12 @@ public ResponseEntity<Map<String, Object>> getAllPosts(
);

List<Map<String, Object>> postMaps = response.getBody();
if (postMaps == null || postMaps.isEmpty()) {
throw new PostNotFoundException("No posts found for the given page: " + page);
}
List<Post> posts = new ArrayList<>();

if (postMaps != null) {

for (Map<String, Object> postMap : postMaps) {
Post post = new Post();
post.setId(((Number) postMap.get("id")).longValue());
Expand All @@ -147,7 +164,7 @@ public ResponseEntity<Map<String, Object>> getAllPosts(
}

fetchAuthorNames(posts);
}


HttpHeaders headers = response.getHeaders();
int totalPosts = Integer.parseInt(Objects.requireNonNull(headers.getFirst("X-WP-Total")));
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> 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<String> 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<String> handlePostNotFoundException(PostNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.nashtech.blogs.analyzer.exception;

public class PostNotFoundException extends RuntimeException {
public PostNotFoundException(String message) {
super(message);
}
}

0 comments on commit 1553ed2

Please sign in to comment.