如何解决无法实例化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
相关产品推荐
相关产品推荐

