1

I have a problem with my exception handling in JSF.

I want to show an error message on my JSF page when the user can not delete an entry in the database.

<h:message for="deleteButton"/>
<h:commandButton id="deleteButton" value="Delete" action="#{filmView.deleteRow(film)}"/>

public void deleteRow(Film deleteTemp) {
  filmService.delete(deleteTemp.getFilmId());
}

public void delete(int id) {
  try {
    em.createQuery("delete from Film where film_id=" + id).executeUpdate();
  } catch (Exception e) {
    FacesContext.getCurrentInstance().addMessage("", new FacesMessage(
    "Removing dataset(ID:" 
     + id + ") is not possible, because it's used in another dataset!"));
    }
}

Is it possible to get this error message into the JSF page and if yes is this better, because I heard that how I do it right now, it is not a good solution.

Emma
  • 27,428
  • 11
  • 44
  • 69
Felix
  • 105
  • 1
  • 2
  • 11
  • 1
    Why is not a good solution? Does it work or not? Try to identify your problem: is it jpa related or jsf? Can you catch the exception? Can you show a Faces Message? – perissf Nov 12 '18 at 16:56
  • @perissf It is working, but my problem is that i went from the bottom layer directly to the view and not go from one layer to another and I thought it would be possible to do the exception handling directly on the view. – Felix Nov 12 '18 at 17:11

1 Answers1

1

Ideally your ManagedBean should handle screen messages:

  1. The best way is throw the error from DAO to your Service layer.

  2. On Service layer you can throw again to your ManagedBean and show the message.


On your FilmDAO.java:

public void delete(int id) throws Exception {
    em.createQuery("delete from Film where film_id=" + id).executeUpdate();
}

On your FilmService.java:

public void delete(int id) throws Exception {
    filmDAO.delete(id);
}

On your FilmMB.java:

try {
  filmService.delete(id);
} catch (Exception e) {
  FacesContext.getCurrentInstance().addMessage("", 
    new FacesMessage("Removing dataset(ID:" + id + ") is not possible, 
                      because it's used in another dataset!"));
}
ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58