使用Spring Boot RESTful API应用程序。它有一个动态表单构建组件,我的事件模型可以对问题进行任意回答。我希望能够在一个POST中提交所有内容。这是有效的,除非用户在答案JSON中提供了无效的问题ID。
POST /events
看起来像这样:
{
"eventTemplate": "http://localhost:8090/eventTemplates/1",
"answers": [
{"question": "http://localhost:8090/questions/1", "value": "Yes" },
],
"location": "The Moon",
"observer": "http://localhost:8090/users/1",
"subject": "http://localhost:8090/users/1",
"timestamp": "2018-03-19T13:26:44.108Z"
}
如果我将“问题”更改为http://localhost:8090/questions/17,则该问题不存在。我想要一个404.但我不明白。我明白了:
{
"cause": {
"cause": {
"cause": null,
"message": null
},
"message": "N/A\n at [Source: org.apache.catalina.connector.CoyoteInputStream@7751c231; line: 4, column: 18] (through reference chain: edu.harvard.h2ms.domain.core.Event[\"answers\"]->java.util.HashSet[0]->edu.harvard.h2ms.domain.core.Answer[\"question\"])"},
"message": "JSON parse error: null; nested exception is com.fasterxml.jackson.databind.JsonMappingException: N/A\n at [Source: org.apache.catalina.connector.CoyoteInputStream@7751c231; line: 4, column: 18] (through reference chain: edu.harvard.h2ms.domain.core.Event[\"answers\"]->java.util.HashSet[0]->edu.harvard.h2ms.domain.core.Answer[\"question\"])"
}
事件实体:
@Entity
public class Event {
@OneToMany(fetch = FetchType.EAGER,
cascade = CascadeType.ALL,
mappedBy = "event")
private Set<Answer> answers = new HashSet<>();
}
回答实体:
@Entity
public class Answer {
@ManyToOne(fetch = FetchType.EAGEr, cascade = CascadeType.ALL)
@JoinColumn(name = "question_id")
private Question question;
}
整个代码库位于https://github.com/stbenjam/h2ms/tree/new-event-model。
任何想法我做错了什么?谢谢!
答案 0 :(得分:0)
您可以做的最具体的事情是自定义异常:
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
...
}
@Controller
public class SomeController {
@RequestMapping.....
public void handleCall() {
if (isFound()) {
// whatever
}
else {
throw new ResourceNotFoundException();
}
}
}
当然还有其他方法:使用@ControllerAdvice
或return new ResponseEntity<>(HttpStatus.NOT_FOUND)
。只是谷歌它,它是相当文件记录。
希望很有帮助:))