0

我创建了一个自定义异常处理。我以为我已经成功了,因为它在 localhost 上显示了错误页面,并且在我使用邮递员时它提供了正确的信息。但是,在我的终端上,它给了我这个错误-> Servlet.service() for servlet [dispatcherServlet] 在路径 [] 的上下文中抛出异常 [请求处理失败;嵌套异常是 org.springframework.web.client.HttpClientErrorException$Conflict: 409 null] 的根本原因。

关于如何解决这个问题的任何建议?谢谢

(请注意,我有一个 Rest Controller 类和 Web 控制器类。)

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = MyDuplicateEntryException.class)
    public ResponseEntity<MyErrorResponse> conflictErrorHandler(MyDuplicateEntryException e) throws IOException {
        return new ResponseEntity<>(new MyErrorResponse(e.getMessage()), CONFLICT);
    }
}


@ResponseStatus(CONFLICT)
public class MyDuplicateEntryException extends RuntimeException {

    public MyDuplicateEntryException(String errorMessage) {
        super(errorMessage);
    }
}

On ServiceImpl:
@Override
    public ResponseEntity<Artist> createArtist(AddArtistForm addArtistForm) throws DuplicateEntryException {

        String artistName = addArtistForm.getName();
        Optional<Artist> artist = artistRepository.findArtistByName(artistName);

        artist.ifPresent(a -> {
            throw new DuplicateEntryException(artist.get().getName() + " already exists");
        });

        return new ResponseEntity<>(artistRepository.save(new Artist(artistName)), CREATED);
    }
4

0 回答 0