Announcement Announcement Module
Collapse
No announcement yet.
Spring Philosophy of Exception Handling Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring Philosophy of Exception Handling

    I am using JSF MyFaces, Spring, Hibernate .
    Any pointers/suggestions on how to modify below code to display user-friendly messages onto browser incase an exception occured in JSF Backing Bean or Spring Bean will be highly appreciated

    JSF Backing Bean:

    public List getDeviceTypeList(){
    try {
    deviceTypes = deviceTypeManager.getDeviceTypeList(); // method call to Spring Bean
    return deviceTypeSelectItems;
    } catch (Exception e) {
    String msg = "Could not retrieve DeviceType List " + e.toString();
    this.logger.error(msg);
    throw new FacesException(msg);
    }
    }

    Spring Bean:

    public List getDeviceTypeList() throws BaseException{
    List deviceTypeList = null;
    try{
    deviceTypeList = deviceTypeDao.findByNamedQuery("findDeviceTypes"); // database call
    } catch (NullPointerException ne) {
    String msg = "Could not retrieve data from Database " + ne.getMessage();
    this.logger.error(msg, ne);
    } catch (Exception e) {
    String msg = "Could not retrieve data from Database " + e.toString();
    this.logger.error(msg, e);
    throw new BaseException(msg, e);
    }
    return deviceTypeList;
    }

    Is it true that Spring advocates against having the signature of business methods with throws exception ???
    For example in my case it is public List getDeviceTypeList() throws BaseException

    Regards
    Bansi

  • #2
    Originally posted by mail2bansi View Post
    Is it true that Spring advocates against having the signature of business methods with throws exception ???
    Spring does not advocate that; you do not add exception in your signatures rather they advocate that you mention them. You can see that by seeing the spring's own code. As a good practice; whether the exceptions are cheked or unchecked you should add them in throws clause so that the caller should know what it is dealing with.

    Regards,

    Imran

    Comment


    • #3
      I think the previous author might have been saying that throwing Exception is bad practice. It is nice to know what the method is throwing be it checked or unchecked, but throwing Exception is a little non-specific. IMHO, it's much better to name specific exceptions.
      Last edited by karldmoore; Aug 29th, 2007, 11:55 AM.

      Comment


      • #4
        Thats right karldmoore
        I am refering to throwing exceptions from business Layer i.e. having business method signature with throws clause
        For example
        public void createManufacturer(NamsManufacturer manuf) throws BaseException;

        Whenever user performs CRUD(Create/Read/Update/Delete) their is a possibility of following Exceptions to occur
        • DataIntegrityViolationException
          DataAccessException
          DoesNotExistException
          AlreadyExistsException

        Now my question is how to do i handle these exceptions in Spring i.e. business layer

        Do i need to define my business methods with throws clause like
        public void createManufacturer(NamsManufacturer manuf) throws BaseException;
        OR is it against the Springs philosophy to define business methods with throws clause

        Any pointers/suggestions will be appreciated

        Regards
        Bansi

        Comment


        • #5
          Further to my earlier posting, i tried producing error by inserting duplicate record . Unfortunately the Spring bean was not able to catch the Exception but the log file shows the following exception
          Code:
          2007-06-04 14:16:20,161 ERROR [org.hibernate.util.JDBCExceptionReporter] - <ORA-00001: unique constraint (NAMS.NAMS_MANUFACTURER_UK) violated
          >
          2007-06-04 14:16:20,161 ERROR [org.hibernate.event.def.AbstractFlushingEventListener] - <Could not synchronize database state with session>
          org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
          Caused by: java.sql.BatchUpdateException: ORA-00001: unique constraint (NAMS.NAMS_MANUFACTURER_UK) violated
          Here is my Spring bean
          Code:
          public void createManufacturer(NamsManufacturer manuf) throws BaseException{
          											
          		if (manuf.getStatus().equalsIgnoreCase("A")){
          			manuf.setStatus("A");
          		}else {
          			manuf.setStatus("I");
          		}
          		/* Moved to JSF Bean
          		manuf.setId(0);
          		manuf.setChangeDate(new Date());
          		Long changeUserId = getChangeUserByUserId();
          		System.out.println("In createManufacture UserId="+changeUserId);
          		
          		NamsUser nu = namsUserDao.get(changeUserId);
          		manuf.setSource("N");
          		manuf.setNamsUser(nu);	
          		*/
          		manuf.setSource("N");
          		try { 
                  manufDao.persist(manuf);       
          		} catch (DataIntegrityViolationException de) {
          			String msg = "Could not save Manufacturer, duplicate Manufacturer id " + de.getMessage();
          			this.logger.error(msg, de);
          			
          			throw new DuplicateManufacturerIdException(msg, de);
          		} catch (Exception e) {
          			String msg = "Could not save Manufacturer " + e.toString();
          			this.logger.error(msg, e);
          			
          			throw new BaseException(msg, e);
          
          		}
          
          	}

          Comment


          • #6
            Are the exceptions you are throwing checked? If they are you'll need to explicitly name them in the transaction configuration (e.g. rollback-for).
            http://www.springframework.org/docs/...dvice-settings
            Last edited by karldmoore; Aug 29th, 2007, 11:55 AM.

            Comment


            • #7
              I am still trying to figure out Exception Handling Mechanism using JSF-Spring-Hibernate.
              Till now this is my understanding ...
              Spring wraps Hibernate Exceptions into Spring specific exceptions . For example Hibernate Exception "org.hibernate.exception.ConstraintViolationExcept ion" is wrapped into Spring Exception "org.springframework.dao.DataIntegrityViolationExc eption" .

              How should i go about Designing exception handling in three layers.

              How do i know which Spring exception is wrapped to Hibernate exception by Spring.???
              Please note i am able to print exception.getCause , but that gives me the cause of Hibernate exception and still i dont know which Spring Exception is wrapped to it. So i looked at spring orm hibernateTemplate API and catching those exception for e.g. DataAccessException, still it doesnt catch the exception

              Comment


              • #8
                If you have a look at the code in SessionFactoryUtils.convertHibernateAccessExceptio n(..) this gives you the coversions.
                Last edited by karldmoore; Aug 29th, 2007, 11:55 AM.

                Comment

                Working...
                X