java - 在 Jsf 中显示有关 SQLIntegrityConstraintViolationException 异常的错误消息

标签 java sql jsf-2 error-handling

我想在我的 jsf 页面中通过 <h:messages/> 通知用户 SQLException。

我有以下功能

 public String createAccount() throws RollbackFailureException,SQLIntegrityConstraintViolationException,Exception{
    String status = "failure";
    EntityManager em = null;
    try {
        logger.log(Level.INFO,"Registering the user");
        utx.begin();
        em = getEntityManager();

        em.persist();
        status = "success";
        utx.commit();

    } catch (Exception ex) {
        try {
            utx.rollback();
        } catch (Exception re) {
            throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
        }
        if (findDetails(details.getId()) != null) {

          throw new SQLIntegrityConstraintViolationException("Your Account cannot be setup as the Login Id already exists.Kindly choose a different Login ID", ex);
        }
        throw ex;
    } finally {
        if (em != null) {
            em.close();
        }

如何用jsf显示错误消息?

谢谢:)

最佳答案

在支持 bean 中使用以下内容来添加消息:

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
...
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
FacesContext.getCurrentInstance().addMessage(null, facesMsg);

严重性也可以是 SEVERITY_WARNSEVERITY_INFO。您可以将 clientId 作为 addMessage 的第一个参数。如果为null,则该消息是全局消息,并显示在h:messages中。

关于java - 在 Jsf 中显示有关 SQLIntegrityConstraintViolationException 异常的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9430748/

相关文章:

java - 如何让用户从 Java Web 应用程序向他/她的 Twitter 帐户发送推文

java - 在关机时停止所有 Spring 批处理作业 (CTRL-C)

mysql - 如何合并列中具有相同值的两个表

sql - 在 PostgreSQL 中查询 iLike 列表

JSF 2.2 导航规则未触发

jsf - 如何创建与正确上下文相关的链接?

Java:两点之间的距离始终返回零

java - 将 JTextField 转换为 int 数组(有异常(exception))

SQL 'select' 具有 3 个条件的查询

javascript - 在 primefaces 数据表上使用监听器执行行单击