我有以下Spring @RestController方法:
public MappingJacksonValue getUserView(User viewer, Long vieweeid) {
User viewee = getUser(vieweeid);
if(viewee == null) throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "entity not found"
);
final MappingJacksonValue result = new MappingJacksonValue(viewee);
Class view = Views.Minimal.class;
if(viewer.getId().equals(viewee.getId())) {
view = Views.Full.class;
}
...some lines omitted...
result.setSerializationView(view);
return result;
}
虽然这工作得很好,但如果没有找到请求的实体,我不高兴抛出一个异常来返回404。
处理这种情况的最佳实践是什么?
如果你愿意,你可以让你的方法返回ResponseEntity<MappingJacksonValue>
,然后返回ResponseEntity.notFound().build()
:
public ResponseEntity<MappingJacksonValue> getUserView(User viewer, Long vieweeid) {
User viewee = getUser(vieweeid);
if(viewee == null) return ResponseEntity.notFound().build();
final MappingJacksonValue result = new MappingJacksonValue(viewee);
Class view = Views.Minimal.class;
if(viewer.getId().equals(viewee.getId())) {
view = Views.Full.class;
}
...some lines omitted...
result.setSerializationView(view);
return ResponseEntity.ok(result);
}