I did a page for adding and viewing activities in a project. The table linked with that page has an UNIQUE constraint for the activity code.
As a result of which when i add a new activity with existing Activity code, it is not accepted and gives a runtime error like this

Error given by Compiler
Internal Exception: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "activity_activity_code_key".

Is there any way with wihich i can implement this as a custom exception so that it gives a error message to the user that " activity code already exists".
I'm attaching the code done by me for activity additon below:
Code for Ui:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:p="http://primefaces.org/ui"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">

    <p:messages/>
    <table width="100%">
        <tr height="10%">
            <td>
                <center><b><h:outputText id="activityInfoH" value="Activity Information" style="font-size: larger;"/></b></center>
            </td>
        </tr>
        <tr height="90%">
            <td>
                <br/>
                <h:outputText id="activityInfo" value="Activity Info" style="font-size: larger;"/>
                <div align="center">
                    <p:panel id="antivityPanel">
                        <h:panelGrid columns="2" cellpadding="10">  
                            <h:outputLabel value="Activity Code (*)" />
                            <p:inputText value="#{activityBean.selectedActivity.activityCode}" required="true" requiredMessage="Activity Code cannot be blank" disabled="#{!activityBean.addMode}"/>

                            <h:outputLabel value="Activity Name (*)" />
                            <p:inputText value="#{activityBean.selectedActivity.activityName}" required="true" requiredMessage="Activity Name cannot be blank"/>

                            <h:outputLabel value="Category" />
                            <p:selectOneMenu value="#{activityBean.selectedSuperActivity}">  
                                <f:selectItems value="#{activityBean.superActivitys}" var="activity" itemLabel="#{activity.toString()}" itemValue="#{activity.activityCode}"/>
                            </p:selectOneMenu>  

                            <h:outputLabel value="Phase" />
                            <p:selectOneMenu value="#{activityBean.selectedPhase}">  
                                <f:selectItems value="#{activityBean.phases}" var="phase" itemLabel="#{phase.toString()}" itemValue="#{phase.phaseCode}"/>
                            </p:selectOneMenu>                              

                            <h:outputLabel value="Description" />
                            <p:inputTextarea value="#{activityBean.selectedActivity.description}"/>

                            <h:outputText value="Billing Type " style="font-size: larger;"/>  
                            <p:selectOneRadio id="options" value="#{activityBean.billable}">  
                                <f:selectItem itemLabel="Billable" itemValue="true" />  
                                <f:selectItem itemLabel="Non-Billable" itemValue="false" />  
                            </p:selectOneRadio>  
                        </h:panelGrid>  
                    </p:panel>
                </div>
                <br/>                        
            </td>
        </tr>
    </table>
    <table align="center">
        <tr>
            <td>
                <h:panelGrid columns="2">
                    <p:commandButton value="Submit" actionListener="#{activityBean.submitActivityInfo}" update=":topForm,:includeForm"/>
                    <p:commandButton value="Cancel" actionListener="#{activityBean.activityPage}" update=":topForm,:includeForm" immediate="true"/>
                </h:panelGrid>
            </td>
        </tr>                            
    </table>
</html>

Code for the backing bean:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thales.tsms.bean.configure;

import com.thales.tsms.bean.navigation.NavigationBean;
import com.thales.tsms.util.Constants;
import com.tsi.eft.beans.ConfigServiceRemote;
import com.tsi.eft.beans.ListingServiceRemote;
import com.tsi.mis.infra.MISException;
import com.tsi.mis.infra.business.model.MISActivity;
import com.tsi.mis.infra.business.model.MISBillingType;
import com.tsi.mis.infra.business.model.MISPhase;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

/**
 *
 * @author tsi0317
 */
@Named
@SessionScoped
public class ActivityBean implements Serializable {

    @EJB
    private ListingServiceRemote listingServiceRemote;
    @EJB
    private ConfigServiceRemote configServiceRemote;
    @Inject
    private NavigationBean navigationBean;
    private MISActivity selectedActivity;
    private List<MISActivity> activityList;
    private boolean enableEdit;
    private List<MISActivity> superActivitys;
    private String selectedSuperActivity;
    private List<MISPhase> phases;
    private String selectedPhase;
    private String billable;
    private boolean addMode;

    public void activityPage() {
        setEnableEdit(true);
        activityList = listingServiceRemote.getAllActivities();
        navigationBean.setNavigationUrl(Constants.SEARCH_ACTIVITY);
        navigationBean.setTitle("Activity Management");
        setSelectedActivity(null);
    }

    public void activityInfoPage() {
        if (selectedActivity.getSuperActivity() != null) {
            setSelectedSuperActivity(selectedActivity.getSuperActivity().getActivityCode());
        }
        setSuperActivitys(listingServiceRemote.getAllSuperActivities());
        setSelectedPhase(selectedActivity.getPhase().getPhaseCode());
        setPhases(listingServiceRemote.getAllPhases());
        if (selectedActivity.getBillingType() != null && "NON_BILLABLE".equals(selectedActivity.getBillingType().name())) {
            setBillable("false");
        } else {
            setBillable("true");
        }
        //navigationBean.setNavigationUrl(Constants.ACTIVITY_INFO);
        //navigationBean.setTitle("Activity Information");
        setAddMode(false);
    }

    public void activityInfoPageByAdd() {
        setBillable("false");
        setSelectedSuperActivity("");
        setSuperActivitys(listingServiceRemote.getAllSuperActivities());
        setSelectedPhase("");
        setPhases(listingServiceRemote.getAllPhases());
        setAddMode(true);
        setSelectedActivity(new MISActivity());
        //navigationBean.setNavigationUrl(Constants.ACTIVITY_INFO);
        //navigationBean.setTitle("Activity Information");
    }

    public void submitActivityInfo() {
        try {
            if (getBillable().equalsIgnoreCase("true")) {
                selectedActivity.setBillingType(MISBillingType.BILLABLE);
            } else {
                selectedActivity.setBillingType(MISBillingType.NON_BILLABLE);
            }

            for (MISPhase phase : phases) {
                if (selectedPhase.equals(phase.getPhaseCode())) {
                    selectedActivity.setPhase(phase);
                    break;
                }
            }

            for (MISActivity activity : superActivitys) {
                if (selectedSuperActivity.equals(activity.getActivityCode())) {
                    selectedActivity.setSuperActivity(activity);
                }
            }

            if (isAddMode()) {
                selectedActivity.setCreatedDate(new Date());
                configServiceRemote.createActivity(selectedActivity);
            } else {
                configServiceRemote.editActivity(selectedActivity);
            }
            FacesContext.getCurrentInstance().addMessage("", new FacesMessage("Activity Saved Successfully"));



        }

        catch (MISException ex) {
            Logger.getLogger(ActivityBean.class.getName()).log(Level.SEVERE, null, ex);
            FacesContext.getCurrentInstance().addMessage("", new FacesMessage(ex.getMessage()));
        }
    }

    public MISActivity getSelectedActivity() {
        return selectedActivity;
    }

    public void setSelectedActivity(MISActivity selectedActivity) {
        this.selectedActivity = selectedActivity;
        if (selectedActivity != null) {
            setEnableEdit(false);
        }
    }

    public List<MISActivity> getActivityList() {
        return activityList;
    }

    public void setActivityList(List<MISActivity> activityList) {
        this.activityList = activityList;
    }

    public boolean isEnableEdit() {
        return enableEdit;
    }

    public void setEnableEdit(boolean enableEdit) {
        this.enableEdit = enableEdit;
    }

    public List<MISActivity> getSuperActivitys() {
        return superActivitys;
    }

    public void setSuperActivitys(List<MISActivity> superActivity) {
        this.superActivitys = superActivity;
    }

    public String getSelectedSuperActivity() {
        return selectedSuperActivity;
    }

    public void setSelectedSuperActivity(String selectedSuperActivity) {
        this.selectedSuperActivity = selectedSuperActivity;
    }

    public List<MISPhase> getPhases() {
        return phases;
    }

    public void setPhases(List<MISPhase> phases) {
        this.phases = phases;
    }

    public String getSelectedPhase() {
        return selectedPhase;
    }

    public void setSelectedPhase(String selectedPhase) {
        this.selectedPhase = selectedPhase;
    }

    public String getBillable() {
        return billable;
    }

    public void setBillable(String billable) {
        this.billable = billable;
    }

    public boolean isAddMode() {
        return addMode;
    }

    public void setAddMode(boolean addMode) {
        this.addMode = addMode;
    }
}

Please give in your inputs regarding this concept..

Edited 4 Years Ago by karthikprs

You can surround the code where that exception is thrown with a try { ...} catch, and catch the org.postgresql.util.PSQLException. In your catch block you can check the exact text of the Exception, and issue error messages or whatever.

This article has been dead for over six months. Start a new discussion instead.