0

I am creating a web application using Spring Boot. In my controller, there can be situations when some errors occur. I need to notify my end users about these errors.

For example there might be an error while saving the data in the database. In this case I need to display a custom error message.

Also sometimes an exception might be thrown, a proper user friendly error message needs to be reported.

I read about using ExceptionHandler to do this. The problem is with this approach, I need to create different views (html files since I am using Thymeleaf) with the error message. So for each exception/error condition, I will need to create a separate HTML file with the hardcoded error message.

Is there anyway whereby a single error.html page can be used and the error message in that page customized depending on the exact error that has occured in the controller?

Patrick
  • 12,336
  • 15
  • 73
  • 115
Revansha
  • 1,923
  • 4
  • 16
  • 21

1 Answers1

0

You can use Springs MVC which means Model View Controlling. So on your page where you have the html to save data to your database, you are able to create html which is only shown if you need it. For example with tymeleafs th:switch or th:if. find more...

In your business logic, you can create a simple pojo like ExecptionMessage where you set your exception message. When a real exception is thrown you can set the particular exception message to this object. In your controller you are now able to set the ExecptionMessage object to your view.

model.addAttribute("execptionMessage", new ExecptionMessage("My Custom message"));

This model is now available in the view and you are able to decide to show the message or not. So no need to create a new html for every error message. But you can think about creating a thymeleaf template to create the html just one time and include the fragment if needed. find more...

<div th:include="footer :: copy">...</div>
M.P.B
  • 9
  • 4
Patrick
  • 12,336
  • 15
  • 73
  • 115