Skip to content

Commit

Permalink
write exception handler in controller and test it successfully
Browse files Browse the repository at this point in the history
  • Loading branch information
nora-kauczor committed Oct 15, 2024
1 parent 6d90dd2 commit 64017bc
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 5 deletions.
4 changes: 4 additions & 0 deletions backend/src/main/java/org/example/backend/ErrorMessage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package org.example.backend;

public record ErrorMessage(String message) {
}
13 changes: 9 additions & 4 deletions backend/src/main/java/org/example/backend/VocabController.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
package org.example.backend;

import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.NoSuchElementException;

@RestController
@RequestMapping("/api/vocab")
Expand All @@ -24,4 +23,10 @@ public List<Vocab> getAllVocabs(){
public Vocab getVocab(@PathVariable String _id){
return vocabService.getVocab(_id);
}

@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoSuchElementException.class)
public ErrorMessage handleElementNotFoundException(){
return new ErrorMessage("No matches for given ID.");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,13 @@ void getVocab_shouldReturnSpecificVocab_whenCalledWithItsId() throws Exception {
"info":"", "language":"Spanish", "reviewDates":[]}
"""));
}

@DirtiesContext
@Test
void getVocab_ShouldTriggerNotFoundStatus_whenCalledWithNonexistentID() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/api/vocab/000"))
.andExpect(status().isNotFound());
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ void getVocab_shouldReturnSpecificVocab_whenCalledWithItsId() {
}

@Test
void getVocab_shouldThrowNoSuchElementException_whenCalledWithNonexistantId() {
void getVocab_shouldThrowNoSuchElementException_whenCalledWithNonexistentId() {
when(mockVocabRepo.findById("000")).thenThrow(NoSuchElementException.class);
assertThrows(NoSuchElementException.class, () -> mockVocabRepo.findById("000"));
verify(mockVocabRepo).findById("000");
Expand Down

0 comments on commit 64017bc

Please sign in to comment.