0

I'm going through this trailhead module and, as a good newbie, I'm experiencing some issues in completing the hands on challenge.

This is my AnimalLocator class:

public with sharing class AnimalLocator {

public void getAnimalNameById(Integer i) {

    HttpResponse resp = makeCallout('https://th-apex-http-callout.herokuapp.com/animals/id', 'GET');
    Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(resp.getBody());
    ////////
    System.debug(results);
    ///////
}

public static HttpResponse makeCallout(String endpoint, String calloutType) {

    Http http = new Http();
    HttpRequest request = new HttpRequest();

    request.setEndpoint(endpoint);
    request.setMethod(calloutType);

    HttpResponse response = http.send(request);
    if (response.getStatusCode() == 200) {
        return response;
    }
}
}

The class isn't finished yet as I still have to go through the parsed json in order to return the animal name by Id. For now, I just want to make the callout, put the results into a map and print such map. I've also changed the return type of the method to void (should be a String) for the purpose of this.

I'm getting the following errors though and can't save the class:

Missing return statement required return type: System.HttpResponse

I'm not sure what I am doing wrong here. Could anyone kindly explain to me what I am doing wrong?

Thanks!

2 Answers 2

2

There is a code path that fails to return a value, specifically if there's an error returned in the callout response (status != 200).

public static HttpResponse makeCallout(String endpoint, String calloutType) {
    Http http = new Http();
    HttpRequest request = new HttpRequest();

    request.setEndpoint(endpoint);
    request.setMethod(calloutType);

    HttpResponse response = http.send(request);
    if (response.getStatusCode() == 200) {
        return response;
    }

    // TODO missing return statement here
}

Exactly what you want to return depends on the "contract" of your makeCallout function. You could have this return the failed response or null, for example, or simply ensure that the function throws an exception. In either case, it is up to the caller to then handle this failure case in an appropriate way.

In essence a method that includes a return type must either return a value or throw an exception in all possible code paths.

1

Method makeCallout returns HttpResponse but code in that method do not ALWAYS return HttpResponse

If returns it only when statusCode equals 200.

When you set your method to return something it needs to always return it.

In your case you need for example move

return response;

outside of conditional (if) block or use else and add second return there.

1
  • True. Silly mistake. Thanks!
    – robruf
    May 28, 2021 at 9:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .