Exceptions that are generated in the same way in many places can simplified by throwing them from inside a helper method.
For example, the following code calls a web service and checks the value of a return code. If the return code is an error it throws an exception.
:
MediaResponse response = webServiceClient.getMedia(mediaId);
if (response.getReturnCode() == response.RETURN_CODE_ERROR)
{
throw new ServiceException(response.getMessage());
}
:
Since there are dozens of calls to the web service, this return code checking is difficult to keep consistent between developers.
Instead, a checkReturnCode method was added:
:
private void checkReturnCode(ServiceResponse response)
throws ServiceException
{
if (response.getReturnCode() == response.RETURN_CODE_ERROR)
{
throw new ServiceException(response.getMessage());
}
}
:
so the calls were much simplified.
:
MediaResponse response = webServiceClient.getMedia(mediaId);
checkReturnCode(response);
:
Later the checkReturnCode could also check an errorCode value in the response.