How can I throw exception from webservice? - java

I am using netbeans to make webservices, I want to make composite webservice using PBEL,
I face a problem in throwing exception in each service, I define complex Type in the schema of the exception I want to throw, and I make it in WSDL too , but inside the service I don't know how can I throw the exception , Here's the example I am working on :
#WebService(serviceName = "CreditCardService", portName = "CreditCardPort", endpointInterface = "org.netbeans.j2ee.wsdl.creditcard.CreditCardPortType", targetNamespace = "http://j2ee.netbeans.org/wsdl/CreditCard", wsdlLocation = "WEB-INF/wsdl/NewWebServiceFromWSDL/CreditCard.wsdl")
public class NewWebServiceFromWSDL implements CreditCardPortType {
public org.netbeans.xml.schema.creditcard.CreditCardResponseType isCreditCardValid(org.netbeans.xml.schema.creditcard.CreditCardType creditCardInfoReq) throws IsCreditCardValidFault {
List<CreditCardType> creditCards = parseCreditCardsFile();
CreditCardResponseType creditCardResponseElement = new CreditCardResponseType();
for (CreditCardType aCreditCard : creditCards) {
if (creditCardInfoReq.getCreditCardNo() == Long.parseLong(String.valueOf(aCreditCard.getCreditCardNo())) {
creditCardResponseElement.setValid(true);
return creditCardResponseElement;
}
}
throws IsCreditCardValidFault(); //here I want to throw an exception .
}
Please can Someone help?

throws IsCreditCardValidFault(); //here I want to throw an exception .
needs to be written as
throw new IsCreditCardValidFault();
throws is used in your declaration of the method, where the throw keyword is used inside the method to indicate where you will throw the exception.
so as an example
try {
//do something which generates an exception
}catch(Exception e){
throw e;
}
but in your case, you want to initiate the exception yourself so you have to create a new object of that exception type. You will create the exception yourself, so no need to enclose in a try/catch block.
throw new IsCreditCardValidFault();

Related

Custom exception not thrown while using spring `#Retryable` annotation

I am trying to implement retry attempts functionality while handling exception using spring-retry. I am using #Retryable as described in my code sample below. But I am facing a strange issue here.
When I use this annotation, it does retry for 3 times which is default, but it does not throw the custom exception, i.e. MyGraphDBServiceException which I have made for my application. Instead, it throws the ArrayIndexOutOfBoundException. When I remove that annotation form the method, I get MyGraphDBServiceException as expected.
How can I ensure that MyGraphDBServiceException gets thrown even when I am using this annotation?
#Override
#Retryable(value = {MyGraphDBServiceException.class, MyGraphDBRedisServiceException.class}, backoff = #Backoff(delay = 1000))
public Long beginTransaction() {
//TODO: provide custom exception handling here
if (configs.isEmpty())
throw new MyGraphDBServiceException(SERVICE_UNAVAILABLE_EXCEPTION);
Long txnId = null;
List<TransactionObject> txnList = new LinkedList<>();
try {
//should throw exception here which should be MyGraphDBServiceException
txnId = txnList.get(0).getTransactionId();
Gson gson = new Gson();
String txnString = gson.toJson(txnList);
redisServiceUtility.add(String.valueOf(txnId), txnString);
} catch (Exception e) {
//TODO: provide custom exception handling here
log.error("[Exception] Caught in redis: {}", e.getMessage());
throw new MyGraphDBServiceException(SERVICE_UNAVAILABLE_EXCEPTION);
}
return txnId;
}
just to be clear, I do get MyGrpahDBServiceException when I run the same code but without #Retryable annotation. So please don't think that my code should throw ArrayIndexOutOfBoundException rather than custom one.

How to properly throw MethodArgumentNotValidException

I'm trying to get the same result as when I use #Valid in object parameter from a Controller. When the object is invalid an exception (MethodArgumentNotValidException) is throw by my ExceptionHandlerController who has #RestControllerAdvice.
In my case I want to validate an object, but I only can validate it in service layer. The object have bean validation annotations, so I'm trying to programmatically throw MethodArgumentNotValidException for my ExceptionHandlerController handle it, but I'm not having success.
So far I have this:
private void verifyCard(CardRequest card) {
BeanPropertyBindingResult result = new BeanPropertyBindingResult(card, "card");
SpringValidatorAdapter adapter = new SpringValidatorAdapter(this.validator);
adapter.validate(card, result);
if (result.hasErrors()) {
try {
throw new MethodArgumentNotValidException(null, result);
} catch (MethodArgumentNotValidException e) {
e.printStackTrace();
}
}
}
The first parameter is from type MethodParameter and I'm not been able to create this object. Is it the best way to handle my problem?
EDIT 1:
I can't remove the try/catch block. When I remove it I get compile error. How to work around?
You have already handled it by the catch block, you should remove try-catch to your global handler catch it.
then specify the method like below
private void verifyCard(CardRequest card) throws MethodArgumentNotValidException
MethodArgumentNotValidException is a subclass of Exception. This means that it's "checked": To throw it out of your verifyCard(..) method, you have to declare that verifyCard(..) can throw it:
private void verifyCard(CardRequest card) throws MethodArgumentNotValidException {
// your code
}
If you have lombok dependency in your project, you can also fake compiler by using #SneakyThrows annotation.
https://projectlombok.org/features/SneakyThrows
throw new MethodArgumentNotValidException(null, result);
Above constructor will not work as method parameter is necessary.
Valid constructor (reference) is:
MethodArgumentNotValidException(MethodParameter parameter, BindingResult bindingResult);
Hence, in your case:
throw new MethodArgumentNotValidException(new MethodParameter(
this.getClass().getDeclaredMethod("verifyCard", YourClassName.class), 0), errors);

Java simple JSON object declaration throws exception

I have a super simple line:
JSONObject params = new JSONObject("{\"values\": { \"barcode\": \"testing\" } }");
Android studio tells me that this line 'throws JSONException', but why? I must be doing something stupid here. Any help is appreciated
JSONException is a checked exception. This means that you need to have code in place to deal with it. You need to either catch the exception or let it bubble up by declaring throws JSONException on your method.
This is the case for all checked exceptions in Java (all exception except those that extend RuntimeException).
In your case, since the String is constant and correct, I would do
} catch ( JSONException e) {
// should never happen
throw new IllegalArgumentException("unexpected parsing error",e);
}
This will convert the JSONException (if for some reason it does happen after all) into an (unchecked) RuntimeException.
public JSONObject(String source) throws JSONException {
this(new JSONTokener(source));
}
You are using above method/constrcutor to create your JSONObject and its saying in its signature that it throws JSONException so you can't simply do what you have done ,
JSONObject params = new JSONObject("{\"values\": { \"barcode\": \"testing\" } }");
You need to enclose above line in Java try- catch since method signature is clearly specifying a checked Exception so you need to handle that in try catch.
try{
JSONObject params = new JSONObject("{\"values\": { \"barcode\": \"testing\" } }");
}catch(JSONException ex){
//eat or rethrow your exception
}
You have to note that there are other JSONObject constructors which doesn't specify any checked exceptions so you can use those in a simple line, like you did but the one you are trying to use specifies a checked exception so you need to handle that - otherwise your code won't compile.

No endpoint java exception

I get the exception : No endpoint.
This is the code:
InsuredDetailsLocator locator_MDP =new InsuredDetailsLocator();
locator_MDP.setInsuredDetailsSoapEndpointAddress("http://mgnt184:8056/MDP_InsuredDetails_WS/InsuredDetails.asmx");
InsuredDetailsSoapStub service = new InsuredDetailsSoapStub();
UpdateInsuredDetails_Input request_MDP =new UpdateInsuredDetails_Input();
request_MDP.setSystemName(urlProps.getProperty(MDP_USERNAME));
request_MDP.setSystemPassword(urlProps.getProperty(MDP_PASSWORD));
request_MDP.setID(11111);
request_MDP.setFAMILY_NAME("hhhh");
request_MDP.setFIRST_NAME("dddd");![enter image description here][1]
request_MDP.setKOD_DIVUR_SHIVUKI_ELC(insuree.getKodDivurShivukiElc());
//I get here the exception :No endpoint
//calling the method:
UpdateInsuredDetails_Output response_MDP= service.recieveMDMDataInsuredDetails(request_MDP);
When the compiler is going to the method: recieveMDMDataInsuredDetails , inside InsuredDetailsSoapStub class - I got the error from there, this is the code inside the method:
public il.co.migdal.ws.tempuri.UpdateInsuredDetails_Output recieveMDMDataInsuredDetails(il.co.migdal.ws.tempuri.UpdateInsuredDetails_Input l_input) throws java.rmi.RemoteException {
if (super.cachedEndpoint == null) {
throw new org.apache.axis.NoEndPointException();
}
.....
You are setting the endpoint on the locator_MDP object but making a call on the service object, which has no relation with locator_MDP (at least in the code posted)

Java / Android: How to work with return type 'List<MyType>'?

My problem is about Java / Android :
I created a class MyClass which has a method getAllData() that returns an List<MyType> = new ArrayList<MyType>(). In an other class MyOtherClass I call to this method and want to write the returned List into another List<MyType>.
But I get the following error: Unhandled exception type Exception
What can I do about this?
Here's the code:
MyClass.java
public List<MyType> datas = new ArrayList<MyType>();
public List<MyType> getAllData() throws Exception{
//add some things to datas...
return datas;
}
MyOtherClass.java
public void fetchData(){
MyClass mydatas = new MyClass();
List<MyType> thedatas = mydatas.getAllData();
}
How can I solve the problem?
With an "try / catch(Exception e)" surrounding the statement, it seems not to get the returned List from getAllData();
Thanks a lot in advance!
You declare the getAllData method to throw Exception. The compiler is now asking you what to do if an exception of type Exception is thrown.
You should NEVER throw Exception as part of a method signature. It is too general. Instead you should try to throw only the specific exceptions that may occur.
If you do not wish fetchData to have to deal with exceptions then you must either declare fetchData to throw the same exceptions OR make getAllData catch the exceptions and return an appropriate value if an exception is thrown.
Since getAllData() might throws a checked exception (i.e., an exception that is not a RunTimeException), you have to surround the statement with try-catch
public void fetchData() {
MyClass mydatas = new MyClass();
try {
List<MyType> thedatas = mydatas.getAllData();
} catch (Exception ex) {
// display or log exception name
}
}
Or add throws clause after the method name.
public void fetchData() throws Exception {
MyClass mydatas = new MyClass();
List<MyType> thedatas = mydatas.getAllData();
}

Categories