import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.DispatcherServlet;
+import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.exceptions.TemplateProcessingException;
import java.util.Optional;
return "view";
}
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
+ @ExceptionHandler(IllegalArgumentException.class)
+ public ModelAndView illegalArgumentException(IllegalArgumentException e)
+ {
+ LOG.error("{}: {}", HttpStatus.BAD_REQUEST, e.getMessage());
+ ModelAndView mav = new ModelAndView("400");
+ mav.addObject("exception", e);
+ return mav;
+ }
+
/**
* This {@link ExceptionHandler @ExceptionHander} is never triggered,
* because the exception is not thrown inside the controller:
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(TemplateProcessingException.class)
- public void templateInputException(TemplateProcessingException e)
+ public ModelAndView templateInputException(TemplateProcessingException e)
{
LOG.error("{}: {}", HttpStatus.BAD_REQUEST, e.getMessage());
+ ModelAndView mav = new ModelAndView("400");
+ mav.addObject("exception", e);
+ return mav;
}
}
--- /dev/null
+<!DOCTYPE HTML>
+<html xmlns:th="http://www.thymeleaf.org">
+ <head>
+ <title th:text="'400: ' + ${exception.getClass().getSimpleName()}">Testing Exception-Handling - Template for 400</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+ </head>
+ <body>
+ <h1 th:text="'400: ' + ${exception.getClass().getSimpleName()}">Template for 400</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>
verify(service, times(0)).checkAnswer(anyInt());
}
+
+ @Test
+ void test400ForExceptionInBusinessLogic() throws Exception {
+ when(service.checkAnswer(anyInt())).thenThrow(new IllegalArgumentException("FOO!"));
+
+ mvc
+ .perform(get(URI.create("http://FOO/?answer=1234")))
+ .andExpect(status().isBadRequest())
+ .andDo((result) -> {
+ String content = result.getResponse().getContentAsString();
+ Document doc = Jsoup.parse(content);
+ assertThat(doc.selectFirst("title").text())
+ .isEqualTo("400: IllegalArgumentException");
+ assertThat(doc.selectFirst("div > p > strong").text())
+ .isEqualTo("Catched exception: java.lang.IllegalArgumentException: FOO!");
+ });
+
+ verify(service, times(1)).checkAnswer(anyInt());
+ }
}