You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决无法实例化HttpStatusCodeException类型的问题

问题解决:Cannot instantiate the type HttpStatusCodeException

HttpStatusCodeException是抽象类,Java不允许直接实例化抽象类,这就是报错的核心原因。

针对你的404 NOT FOUND场景,可改用它的具体实现子类来抛出异常,以下是两种常用写法:

方案1:使用HttpClientErrorException指定状态码

public CommitResponse getOneCommitInfo(String commitHash) {
    CommitResponse commit = new CommitResponse();
    for (int i = 0; i < allCommitsList.size(); i++) {
        if (((CommitResponse) allCommitsList.get(i)).getHash().equals(commitHash)) {
            commit = (CommitResponse) allCommitsList.get(i);
            return commit;
        }
    }
    throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
}

方案2:使用更具体的NotFound子类(Spring 5.3+支持)

public CommitResponse getOneCommitInfo(String commitHash) {
    CommitResponse commit = new CommitResponse();
    for (int i = 0; i < allCommitsList.size(); i++) {
        if (((CommitResponse) allCommitsList.get(i)).getHash().equals(commitHash)) {
            commit = (CommitResponse) allCommitsList.get(i);
            return commit;
        }
    }
    throw new HttpClientErrorException.NotFound();
}

额外优化:你可以把循环改成增强for循环,让代码更简洁:

public CommitResponse getOneCommitInfo(String commitHash) {
    for (Object obj : allCommitsList) {
        CommitResponse commit = (CommitResponse) obj;
        if (commit.getHash().equals(commitHash)) {
            return commit;
        }
    }
    throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
}

内容的提问来源于stack exchange,提问作者Tindona

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:41:12