I want to show my custom exception that is being thrown in Java code in Thymeleaf.
@Override
public UserDetails loadUserByUsername(String benutzername) throws UsernameNotFoundException {
Benutzer benutzer = userRepository.findByBenutzername(benutzername);
if (benutzer == null || ! benutzer.isActive()) {
throw new UsernameNotFoundException("Wrong username or password was provided!");
}
<div th:if="${param.error}" >
<div class="alert alert-danger">
Here should my custom exception appear from above.
</div>
</div>
I throw a new UsernameNotFoundException with a custom exception and this exception should be shown in my template, however, I do not know how this should be done.
Define the property in application.properties to enable the stacktrace to be included as expression attribute in Thymeleaf view.
server.error.include-stacktrace=always
and then create an error page named error.html
like below.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<style>
table td{
vertical-align:top;
border:solid 1px #888;
padding:10px;
}
</style>
</head>
<body>
<h1>My Thymeleaf Error Page</h1>
<table>
<tr>
<td>Date</td>
<td th:text="${timestamp}"/>
</tr>
<tr>
<td>Path</td>
<td th:text="${path}"/>
</tr>
<tr>
<td>Error</td>
<td th:text="${error}"/>
</tr>
<tr>
<td>Status</td>
<td th:text="${status}"/>
</tr>
<tr>
<td>Message</td>
<td th:text="${message}"/>
</tr>
<tr>
<td>Exception</td>
<td th:text="${exception}"/>
</tr>
<tr>
<td>Trace</td>
<td>
<pre th:text="${trace}"/>
</td>
</tr>
</table>
</body>
</html>
Refer this for full example.