Manual exception handling by programmers can be inconsistent, even when very clearly specified in developer standards.  For example, how do you treat all the different exceptions that can result from a web service call?

For example, a RemoteException can be thrown by the web server with another exception inside it.  Other exceptions are more serious and mean that the web service could not be reached at all and the action should not continue.

public Media getMedia(String mediaId) throws ServiceException
{
    try
    {
        GenappWebService client = getWebServiceClient();
        MediaResponse response = client.getMedia(mediaId);
        checkReturnCode(response);
        return response.getMedia();
    }
    catch (RemoteException e)
    {
        logger.error("Error accessing web service.", e);
        throw new ServiceException(e);
    }
    catch (ServiceException e)
    {
        handleException(e);
        throw e;
    }
    catch (Exception e)
    {
        logger.error(e);
        e.printStackTrace();
        throw new ServiceException(e.getMessage());
    }
}

    

private void handleException(Exception e) throws ServiceException
{
    if (e instanceof RemoteException)
    {
        RemoteException re = (RemoteException)e;
        if (re.getCause() != null)
        {
            logger.error("Internal exception in web server", re);
        }
        else
        {
            logger.error("Web service unavailable. Serious", e);
        }
        throw new CantContinueException("Web Service failure");
    }
    else if (e instanceof ServiceException)
    {
        throw (ServiceException)e;
    }
    else
    {
        logger.error("Problem calling web service", e);
        throw new ServiceException(e.getMessage());
    }
}

Which means every call is simplified:

public Media getMedia(String mediaId) throws ServiceException
{
    try
    {
        GenappWebService client = getWebServiceClient();
        MediaResponse response = client.getMedia(mediaId);
        checkReturnCode(response);
        return response.getMedia();
    }
    catch (Exception e)
    {
        handleException(e);
    }
    return null;
}

.

blog comments powered by Disqus