1

I have two modules, one calls the other from a rest template. ( admin calls notifServer) the notifServer has a method annotated with @Async . I want to throw an exception in that method, but the admin gets the response too quickly and the exception method cannot be caught at admin.

I an new to spring and the @Async process. I've tried mapping the response body from the NotifServer to a CCompletableFuture.class . But Still I get no error response.

This code is from admin

ResponseEntity response = fcmRestTemplate.exchange(nsUrl + "/fcm/admin/" + bulkFcmId, HttpMethod.POST,
                    HttpEntityUtils.getHttpEntity(moduleCode), CompletableFuture.class);
            if (response.getStatusCode() != HttpStatus.CREATED && response.getStatusCode() != HttpStatus.ACCEPTED) {
                String errorMessage = ErrorResourceUtil.getErrorMessage((HashMap) response.getBody(),"Unable to send fcm");
                setStatusToFailedByBulkFcmId(bulkFcmId);
                throw new ClientException(errorMessage);
            }

now this is from NotifServer

JobExecution jobExecution = jobLauncher
                    .run(importJob, new JobParametersBuilder()
                    .addString("fullPathFileName", TMP_DIR)
                    .addString("batch_fcm_id", String.valueOf(id))
                    .addLong("time",System.currentTimeMillis())
                    .toJobParameters());
            if(jobExecution.getStepExecutions().stream().map(StepExecution::getStatus).findFirst().get().equals(BatchStatus.ABANDONED)){
             throw new ClientException("INVALID CSV");

This is annotated with @Async.

So is there a way for me to catch the client exception in the response body in the Admin?

EDIT This is the API from notifServer

@ResponseStatus(HttpStatus.CREATED)
    @PostMapping(value = "/admin/{bulkFcmId}")
    public void pushFCMByAdmin(@PathVariable Long bulkFcmId) {
        fcmService.sendFcmByAdmin(bulkFcmId, AuthUtil.getCurrentUser());
    }

Then the sendFcmByAdmin has @Async annotation.

4
  • I guess Rest API on the NotifServer is not waiting for async call to finish and returns immediately. Can you update the post with complete API code from the NotifServer .
    – Sanj
    Apr 5, 2019 at 5:24
  • I have edited with the controller from notifServer, the sendFcmByAdmin is a void method which calls the batch job and pushFcm method. Apr 5, 2019 at 5:32
  • and sendFcmByAdmin has @Async?
    – Sanj
    Apr 5, 2019 at 5:36
  • yes sir! That method has @Async Apr 5, 2019 at 5:37

1 Answer 1

0

In below code can you provide the return type to be a business object rather than CompletableFuture.class.Since you are passing CompletableFuture.class as a parameter to the exchange it expects a response return value of the type CompletableFuture.class.

ResponseEntity response = fcmRestTemplate.exchange(nsUrl + "/fcm/admin/" + bulkFcmId, HttpMethod.POST,
                        HttpEntityUtils.getHttpEntity(moduleCode), CompletableFuture.class);
                if (response.getStatusCode() != HttpStatus.CREATED && response.getStatusCode() != HttpStatus.ACCEPTED) {
                    String errorMessage = ErrorResourceUtil.getErrorMessage((HashMap) response.getBody(),"Unable to send fcm");
                    setStatusToFailedByBulkFcmId(bulkFcmId);
                    throw new ClientException(errorMessage);
                }

Instead of passing Completable Future ,can you try creating it as follows:

Use an asynchronous method to make the rest template call in admin:

@Async
public CompletableFuture<List<BusinessObject>> getResponseAsynchronously(String value) {
    String url = "https://restendpoint.eu/rest/v2/lang/" + value + "?fields=name";
    BusinessObject[] response = restTemplate.getForObject(url, Country[].class);
    return CompletableFuture.completedFuture(Arrays.asList(response));
}

then in the controller read the CompletableFuture like:

@GetMapping("")
public List<String> getAllDataFromRestCall() throws Throwable {

    CompletableFuture<List<BusinessObject>> businessObjectsFuture = countryClient.getResponseAsynchronously("fr");
    List<String> europeanFrenchSpeakingCountries;

            try {
                europeanFrenchSpeakingCountries = new ArrayList<>(businessObjectsFuture
                .get()
                .stream()
                .map(Country::getName)
                .collect(Collectors.toList()));

     } catch (Throwable e) {
       throw e.getCause();
     }

   return europeanFrenchSpeakingCountries;
}
2
  • I tried it but it goes synchronous basically, so what is the point of using @Async Apr 7, 2019 at 4:18
  • Can you please provide more details like stacktrace so that we may analyze the issue more. So the requests are getting triggered synchronously even after using completable future to call the method? Apr 7, 2019 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.