import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.ResponseStatus;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.servlet.DispatcherServlet;
+import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.exceptions.TemplateInputException;
import java.util.Optional;
return "view";
}
+ @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+ @ExceptionHandler(IllegalArgumentException.class)
+ public ModelAndView illegalArgumentException(IllegalArgumentException e)
+ {
+ LOG.error("{}: {}", HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
+ ModelAndView mav = new ModelAndView("resolved");
+ mav.addObject("exception", e);
+ return mav;
+ }
+
+ /**
+ * This {@link ExceptionHandler @ExceptionHander} is never triggered,
+ * because the exception is not thrown inside the controller:
+ * <strong>It is functionless!</strong>
+ * <p>
+ * The exception is thrown by Thymeleaf, which is called by the
+ * {@link DispatcherServlet} after the controller has finished its
+ * work during the rendering of the outcome.
+ * </p>
+ * <p>
+ * {@link ExceptionHandler @ExceptionHander's} are not able, to catch
+ * and resolve exceptions, which are thrown outside of the scope of the
+ * controller.
+ * This is also true for {@link ControllerAdvice}.
+ * </p>
+ */
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(TemplateInputException.class)
- public void templateInputException(TemplateInputException e)
+ public ModelAndView templateInputException(TemplateInputException e)
{
LOG.error("{}: {}", HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
+ ModelAndView mav = new ModelAndView("resolved");
+ mav.addObject("exception", e);
+ return mav;
}
}
--- /dev/null
+<!DOCTYPE HTML>
+<html xmlns:th="http://www.thymeleaf.org">
+ <head>
+ <title th:text="'503: ' + ${exception.getClass().getSimpleName()}">Testing Exception-Handling - Template for 503</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+ </head>
+ <body>
+ <h1 th:text="'503: ' + ${exception.getClass().getSimpleName()}">Template for 503</h1>
+ <div>
+ <p><strong th:text="'Catched exception: ' + ${exception}">EXCEPTION</strong></p>
+ <p><a href="#" th:href="@{/}">Back to HOME</a></p>
+ </div>
+ </body>
+</html>