Denis Denis - 10 days ago 6
HTTP Question

How to force the server to send back an HTTP error 500 when my HealthIndicator returns DOWN

I have a this HSMHealthIndicator.java class which does NOT implement HealthIndicator :

@Component
public class HSMHealthIndicator {

/* constructor */
public HSMHealthIndicator() {

setServiceFactory(Application.getServiceFactory());
errorMessage = "";
}

public Health health() {

if (checkHSMStatus() != 0) {
return Health.down().withDetail("Error Code", checkHSMStatus()).build();
}
return Health.up().build();
}

private int checkHSMStatus() {
try {
serviceFactory.getService().ping();
}
catch (Exception e){
logger.error("Exception", e);
setErrorMessage(e.getMessage());
return 1;
}
return 0;
}

....
}


This HealthIndicator is used by a HSMandDbEndpoint class implementing the Endpoint interface :

public class HSMandDbEndpoint implements Endpoint {

private String host;
private int port;

public HSMandDbEndpoint(String host, int port) {
this.host = host;
this.port = port;
}

...

@Override
public String invoke() {

StringBuilder sb = new StringBuilder();
HSMHealthIndicator h = new HSMHealthIndicator();
h.setHost(getHost());
h.setPort(getPort());
Status s = h.health().getStatus();
sb.append("Status of the HSM : " + s.getCode());
if (Status.DOWN.getCode().equalsIgnoreCase(s.getCode()))
sb.append(" - " + h.getErrorMessage());
return sb.toString();
}
}


When I do some tests with an IP address different from the HSM's one, I have "DOWN" as expected. But I have code 200 in the HTTP response. I would like that it sends back an HTTP error 500. How can I do?

Answer

That should probably be a 503 not a 500. Your invoke method should return a ResponseEntity. You can look at the source code of HealthMvcEndpoint for more details.