115. Exception Handling with @ResponseStatus, @ExceptionHandler - dkkahm/study-springfamework5 GitHub Wiki

@ResponseStatus

  • Custom Exception
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {
    public NotFoundException() {
        super();
    }

    public NotFoundException(String message) {
        super(message);
    }

    public NotFoundException(String message, Throwable cause) {
        super(message, cause);
    }
}
  • Controller
    @GetMapping("/{id}")
    public String getRecipe(@PathVariable Long id, Model model) throws Exception {
        Recipe recipe = recipeService.findById(id);
        model.addAttribute("recipe", recipe);
        return "show_recipe";
    }
  • Service
    public Recipe findById(Long id) {
        return recipeRepository.findById(id).orElseThrow(() -> new NotFoundException("Recipe Not Found"));
    }
  • Test
    @Test
    void getRecipe() throws Exception {
        when(recipeService.findById(anyLong())).thenThrow(NotFoundException.class);

        mockMvc.perform(get("/recipe/1"))
                .andExpect(status().isNotFound());
    }

@ExceptionHandler

  • Controller
@Controller
@RequestMapping("/recipe")
public class RecipeController {

    ....

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NotFoundException.class)
    public ModelAndView handleNotFound() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("404error");
        return modelAndView;
    }