有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在我的HealthIndicator返回时强制服务器发回HTTP错误500

我有这个健康指标。未实现HealthIndicator的java类:

@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;
    }

    ....
} 

此HealthIndicator由实现端点接口的HSMandDbEndpoint类使用:

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();
        }
 }

当我使用不同于HSM的IP地址进行一些测试时,我会像预期的那样“停机”。但是我在HTTP响应中有代码200。我希望它发回HTTP错误500。我该怎么办


共 (1) 个答案

  1. # 1 楼答案

    这应该是一个503而不是一个500。你的invoke方法应该返回一个ResponseEntity。您可以查看the source code of ^{}了解更多详细信息