vendredi 19 juin 2020

Java Spring Boot Web App: Handling 404 Exception

I'm going through a Java Spring Boot tutorial and am in the middle of trying to handle 404 exceptions. I have the exact code as in the tutorial, but for some reason it isn't working, although the 403 error is working. In the tutorial, the way the instructor handles all outstanding exceptions is with the following, specifically defaultErrorHandler(). However, this is not working:

@ControllerAdvice
public class GlobalExceptionHandler {

    @Value("${message.error.exception}")
    private String exceptionMessage;

    @Value("${message.error.duplicate.user}")
    private String duplicateUserMessage;

    @ExceptionHandler(value=Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.getModel().put("message", exceptionMessage);
        modelAndView.getModel().put("url", req.getRequestURL());
        modelAndView.getModel().put("exception", e);
        modelAndView.setViewName("app.exception");
        return modelAndView;
    }

    @ExceptionHandler(value=DataIntegrityViolationException.class)
    public ModelAndView duplicateUserHandler(HttpServletRequest req, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.getModel().put("message", duplicateUserMessage);
        modelAndView.getModel().put("url", req.getRequestURL());
        modelAndView.getModel().put("exception", e);
        modelAndView.setViewName("app.exception");
        return modelAndView;
    }
}

I then tried to add something similar to what the instructor has for handling 403 errors, found below, but this is not working either:

    @RequestMapping("/403")
    ModelAndView accessDenied(ModelAndView modelAndView) {
        System.out.println("We're here");
        modelAndView.getModel().put("message", accessDeniedMessage);
        modelAndView.setViewName("app.message");
        return modelAndView;

    }

    @RequestMapping("/404")
    ModelAndView pageNotFound(ModelAndView modelAndView) {

        modelAndView.getModel().put("message", exceptionMessage);
        modelAndView.setViewName("app.message");
        return modelAndView;

    }

I've tried to debug by putting System.out.println("test") in each of the suspected methods, but none of them have been reached. Any help would be appreciated. Thanks!




Aucun commentaire:

Enregistrer un commentaire