Skip to content
This repository has been archived by the owner on Jul 23, 2024. It is now read-only.

Commit

Permalink
Handle exception globally
Browse files Browse the repository at this point in the history
Signed-off-by: Moti Asayag <[email protected]>
  • Loading branch information
masayag authored and openshift-merge-robot committed May 23, 2023
1 parent 88e1b7a commit b79debd
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 16 deletions.
42 changes: 41 additions & 1 deletion notification-service/generated/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@
}
},
"description" : "Bad Request"
},
"404" : {
"content" : {
"*/*" : {
"schema" : {
"$ref" : "#/components/schemas/ErrorMessageDTO"
}
}
},
"description" : "Not Found"
}
},
"tags" : [ "Notification Message" ]
Expand Down Expand Up @@ -138,6 +148,16 @@
}
},
"description" : "Forbidden"
},
"404" : {
"content" : {
"*/*" : {
"schema" : {
"$ref" : "#/components/schemas/ErrorMessageDTO"
}
}
},
"description" : "Not Found"
}
},
"summary" : "Return a list of notification records for the user",
Expand Down Expand Up @@ -199,6 +219,16 @@
}
},
"description" : "Forbidden"
},
"404" : {
"content" : {
"*/*" : {
"schema" : {
"$ref" : "#/components/schemas/ErrorMessageDTO"
}
}
},
"description" : "Not Found"
}
},
"summary" : "Return the number of the unread notification records for the user",
Expand Down Expand Up @@ -236,6 +266,16 @@
},
"403" : {
"description" : "Forbidden"
},
"404" : {
"content" : {
"*/*" : {
"schema" : {
"$ref" : "#/components/schemas/ErrorMessageDTO"
}
}
},
"description" : "Not Found"
}
},
"summary" : "Delete the specified notification record",
Expand Down Expand Up @@ -295,7 +335,7 @@
"content" : {
"*/*" : {
"schema" : {
"$ref" : "#/components/schemas/NotificationRecordResponseDTO"
"$ref" : "#/components/schemas/ErrorMessageDTO"
}
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import com.redhat.parodos.notification.exceptions.NotificationRecordNotFoundException;
import com.redhat.parodos.notification.exceptions.UnsupportedStateException;
import com.redhat.parodos.notification.exceptions.UsernameNotFoundException;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice
public class ControllerExceptionHandler {
Expand All @@ -32,6 +37,27 @@ public ErrorMessageDTO handleConstraintViolationException(ConstraintViolationExc
return message;
}

@ExceptionHandler(value = { UsernameNotFoundException.class, NotificationRecordNotFoundException.class })
@ResponseBody
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public ErrorMessageDTO resourceNotFoundException(UsernameNotFoundException ex, WebRequest request) {
return new ErrorMessageDTO(new Date(), ex.getMessage(), "Resource not found");
}

@ExceptionHandler(value = { UnsupportedStateException.class })
@ResponseBody
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ErrorMessageDTO unsupportedStateException(UnsupportedStateException ex, WebRequest request) {
return new ErrorMessageDTO(new Date(), ex.getMessage(), "Unsupported notification state");
}

@ExceptionHandler(value = { UnsupportedOperationException.class })
@ResponseBody
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ErrorMessageDTO unsupportedOperationException(UnsupportedStateException ex, WebRequest request) {
return new ErrorMessageDTO(new Date(), ex.getMessage(), "Unsupported operation");
}

record ErrorMessageDTO(Date date, String message, String description) {
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
*/
package com.redhat.parodos.notification.exceptions;

import java.util.UUID;

/**
* The NotificationRecordNotFoundException wraps unchecked standard Java exception and
* enriches them with a custom error code. You can use this execution when there is a miss
Expand All @@ -27,8 +29,8 @@ public class NotificationRecordNotFoundException extends RuntimeException {

private static final long serialVersionUID = 1L;

public NotificationRecordNotFoundException(String message) {
super(message);
public NotificationRecordNotFoundException(UUID id) {
super("Notification record not found: %s".formatted(id));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@
package com.redhat.parodos.notification.exceptions;

/**
* The StateNotFoundOrUnsupportedException wraps unchecked standard Java exception and
* enriches them with a custom error code. You can use this execution when a Notification
* State is not found or is unsupported.
* The UnsupportedStateException is used when a Notification State is not found or is
* unsupported.
*
* @author Gloria Ciavarrini (Github: gciavarrini)
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ public class UsernameNotFoundException extends RuntimeException {

private static final long serialVersionUID = 1L;

public UsernameNotFoundException(String message) {
super(message);
public UsernameNotFoundException(String username) {
super("Username not found: %s".formatted(username));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import com.redhat.parodos.notification.enums.State;
import com.redhat.parodos.notification.exceptions.NotificationRecordNotFoundException;
import com.redhat.parodos.notification.exceptions.UnsupportedStateException;
import com.redhat.parodos.notification.exceptions.UsernameNotFoundException;
import com.redhat.parodos.notification.jpa.entity.NotificationMessage;
import com.redhat.parodos.notification.jpa.entity.NotificationRecord;
import com.redhat.parodos.notification.jpa.entity.NotificationUser;
Expand All @@ -33,13 +34,11 @@
import com.redhat.parodos.notification.service.NotificationRecordService;
import com.redhat.parodos.notification.util.SearchUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;

/**
* @author Richard Wang (Github: RichardW98)
Expand Down Expand Up @@ -136,7 +135,7 @@ private NotificationUser getNotificationUser(String username) {
Optional<NotificationUser> notificationsUser = this.notificationUserRepository.findByUsername(username);
if (notificationsUser.isEmpty()) {
log.error("Unable to find the username:{}", username);
throw new ResponseStatusException(HttpStatus.SC_NOT_FOUND, "Username not found: " + username, null);
throw new UsernameNotFoundException(username);
}
return notificationsUser.get();
}
Expand All @@ -156,8 +155,7 @@ private NotificationRecord updateArchiveFolder(UUID id) {
private Optional<NotificationRecord> findRecordById(UUID id) {
Optional<NotificationRecord> notificationsRecordOptional = this.notificationRecordRepository.findById(id);
if (notificationsRecordOptional.isEmpty()) {
throw new NotificationRecordNotFoundException(
String.format("Could not find NotificationRecord for id = %s", id));
throw new NotificationRecordNotFoundException(id);
}
return notificationsRecordOptional;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import com.redhat.parodos.notification.exceptions.NotificationRecordNotFoundException;
import com.redhat.parodos.notification.exceptions.SearchByStateAndTermNotSupportedException;
import com.redhat.parodos.notification.exceptions.UnsupportedStateException;
import com.redhat.parodos.notification.exceptions.UsernameNotFoundException;
import com.redhat.parodos.notification.jpa.entity.NotificationMessage;
import com.redhat.parodos.notification.jpa.entity.NotificationRecord;
import com.redhat.parodos.notification.jpa.entity.NotificationUser;
Expand All @@ -39,7 +40,6 @@
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
Expand Down Expand Up @@ -100,7 +100,7 @@ void getNotificationRecords() {

// Notification User doesn't exist
when(this.notificationUserRepository.findByUsername(userName)).thenReturn(emptyOptional);
Exception exception = assertThrows(ResponseStatusException.class, () -> {
Exception exception = assertThrows(UsernameNotFoundException.class, () -> {
this.notificationRecordServiceImpl.getNotificationRecords(pageable, userName, State.UNREAD, searchTerm);
});

Expand Down Expand Up @@ -203,7 +203,7 @@ void updateNotificationStatus() {
Exception exception = assertThrows(NotificationRecordNotFoundException.class, () -> {
this.notificationRecordServiceImpl.updateNotificationStatus(uuid, operation);
});
assertEquals(String.format("Could not find NotificationRecord for id = %s", uuid), exception.getMessage());
assertEquals("Notification record not found: %s".formatted(uuid), exception.getMessage());
}

// Test READ operation and record exists
Expand Down

0 comments on commit b79debd

Please sign in to comment.