我有这个枚举结构,用于存储错误响应:

public enum ErrorDetail implements CjmErrorInfo {

    JOURNEY_NOT_FOUND("1000", "not found", "not found", "not found", HttpStatus.NOT_FOUND),

    private String errorCode;
    private String message;
    private String detail;
    private String title;
    private HttpStatus httpStatus;

    public String getErrorCode()
    {
        return this.errorCode;
    }

    public HttpStatus getHttpStatus(){
        return this.httpStatus;
    }
}


但是我想基于错误代码获取http状态(HttpStatus.NOT_FOUND)。如何实现呢?

最佳答案

您可以将静态方法添加到您的enum中,如下所示:

  public static ErrorDetail getByErrorCode(String errorCode) {
    return Arrays.stream(Test.values()).filter(errorDetail -> errorDetail.getErrorCode().equals(errorCode))
        .findFirst().orElse(null);
  }


顺便说一句,您的enum缺少构造函数!需要在枚举常量上定义所有这些字段,否则将无法编译。

10-04 22:47