Thursday, 2 April 2015

Handling SOAP Faults

When we invoke a web service operation it may give proper response or throw an exception. So far we have seen web service giving a proper response. How to use exception in web service? How our addEmployee operation throws a user defined exception when it receives a NULL value? Lets see.

EmployeeService.java (service interface)

package com.sri.service;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

import com.sri.model.Employee;

@WebService
@SOAPBinding(style=Style.DOCUMENT)
public interface EmployeeService {

       @WebMethod
       public void addEmployee(Employee e) throws Exception;
       @WebMethod
       public Employee[] getEmployees();
}

EmployeeServiceImpl.java (Service Implementation)

package com.sri.service;

import java.util.ArrayList;

import javax.jws.WebService;

import com.sri.model.Employee;

@WebService(endpointInterface="com.sri.service.EmployeeService")
public class EmployeeServiceImpl implements EmployeeService{

       private ArrayList<Employee> employee;
       @Override
       public void addEmployee(Employee e) throws Exception {

              if(e == null){
                     throw new InvalidEmployeeException("Employee object is NULL");
              }
              if(employee == null)
                     employee = new ArrayList<Employee>();
              employee.add(e);
       }

       @Override
       public Employee[] getEmployees() {
              return (Employee[])employee.toArray();
       }

}

InvalidEmployeeException.java (User defined exception)

package com.sri.service;

public class InvalidEmployeeException extends Exception {

       public InvalidEmployeeException(String errorMsg){
              super(errorMsg);
       }
}


After deploy this service you can see WSDL updated with the exception details.
Along with input and output messages, the exception message also declared.


As we throw only one exception, one exception message has been defined. If we throw more than one exception then as many number of exception messages would be defined in the WSDL.



Types information also defined for the corresponding exception message in the types section.