Spring Boot中出现500内部服务器错误而不是404

时间:2018-05-03 16:56:48

标签: java spring spring-boot

当我试图找出数据库中没有的值时,我得到500内部服务器错误。我已经提供了抛出ResourceNotFoundException错误的逻辑,但是,由于某些原因它没有工作。我需要做些什么才能获得404 ResourceNotFoundException而不是500 Internal Server Error。 这是我的代码:

@PostMapping("/start/{id}")
    public ResponseEntity<String> startEvent(@PathVariable() Long id) {
        Event event = this.eventRepository.findById(id).get();

        if (event == null) {
            throw new ResourceNotFoundException("Event with id " + id + " not found.");
        }

        event.setStarted(true);
        this.eventRepository.save(event);

        return ResponseEntity.ok("Event " + event.getName() + " has started");
    }

我想eventRepository.findById(id)// id = 200返回500响应,因为数据库中不存在id为200的记录。我该怎么做才能获得ResourceNotFoundException?

2 个答案:

答案 0 :(得分:3)

eventRepository.findById返回Optional(在Spring Data JPA 2.0.6中,请参阅https://docs.spring.io/spring-data/jpa/docs/2.0.6.RELEASE/reference/html/#repositories.core-concepts

Optional.get空选项导致NoSuchElementExceptionhttps://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#get--)。您的if (event == null)来得太晚了。 检查stactrace,您应该看到该异常来自this.eventRepository.findById,实际异常为NoSuchElementException

要解决此问题,您应将代码更改为

    Optional<Event> optionalEvent= this.eventRepository.findById(id);
    if (!optionalEvent.isPresent()) {
        throw new ResourceNotFoundException("Event with id " + id + " not found.");
    }
 Event event=optionalEvent.get();
 //the rest of your logic

您也可以用更实用的方式编写代码

Event event = this.eventRepository
.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Event with id " + id + " not found."))

<强>摘要

请勿在{{1​​}}上致电get()而不检查它是否存在(使用Optional方法)

答案 1 :(得分:1)

eventRepository.findById()返回Optional 因此,您必须在get()

之前测试是否存在
Optional<Event> optEvent = eventRepository.findById();
if (!optEvent.isPresent()) {
 //throw exception here   
}