【发布时间】:2019-09-26 03:36:34
【问题描述】:
在我的 API 中,我喜欢保护用户详细信息端点,以便正常登录的用户只能访问他们的用户资料。因此我正在编写控制器:
@RequestMapping(value = URL_USER + "/{id}", method = RequestMethod.GET)
@ResponseBody
public PersistentEntityResource get(PersistentEntityResourceAssembler persistentEntityResourceAssembler, @PathVariable Long id) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ApplicationUser loggedInUser = applicationUserService.findByUsername(authentication.getName());
ApplicationUser applicationUser = applicationUserService.findById(id);
if (applicationUser.getId().equals(loggedInUser.getId())) {
return persistentEntityResourceAssembler.toFullResource(applicationUser);
}
throw new IllegalAccessException();
}
与其引发导致InternalServerExcetption 的异常,我更喜欢返回默认的spring boot 错误json,如下所示:
{
"timestamp": "2019-05-08T11:42:23.064+0000",
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/user/2"
}
我希望有一个解决方案,它也适用于 404 等其他错误。实现该目标的最简单方法是什么?
【问题讨论】:
-
您可以使用
@ControllerAdvice和@ExceptionHandler来实现这一点,就像我在this question 中提到的那样 -
这行不通,因为我喜欢继续返回
PersistentEntityResource而不是ResponseEntity -
这样的换行有什么问题吗?
ResponseEntity<PersistentEntityResource> -
还没试过,不过找到了一个解决方案,貌似最优雅
标签: java rest spring-boot