在我的API中,我想保护用户详细信息端点,以便普通登录用户只能访问其用户个人资料。为此,我正在编写控制器:
match(do.call(paste, as.data.frame(a)), do.call(paste, as.data.frame(b)))
#[1] 4 1
我想返回默认的spring boot error json,而不是引发导致@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
我希望有一个解决方案,该解决方案对其他类似404的Erros一样有效。实现该目标的最简单方法是什么?
答案 0 :(得分:0)
您可以对同一方法使用以下方法
public class FooController{
//...
@ExceptionHandler({ CustomException1.class, CustomException2.class })
public String handleException() {
return "the intended body";
}
}
或者,您可以使用@ControllerAdvice
@ControllerAdvice
public class RestResponseEntityExceptionHandler
extends ResponseEntityExceptionHandler {
@ExceptionHandler(value
= { IllegalArgumentException.class, IllegalStateException.class })
protected ResponseEntity<Object> handleConflict(
RuntimeException ex, WebRequest request) {
String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse,
new HttpHeaders(), HttpStatus.CONFLICT, request);
}
}
答案 1 :(得分:0)
经过一番研究,我发现了一个看起来很优雅的解决方案:
RestController方法看起来像这样:
@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 ForbiddenRequestException("Access not allowed");
}
另外,我已经实现了ForbiddenRequestException
类:
@ResponseStatus(value = HttpStatus.FORBIDDEN)
public class ForbiddenRequestException extends RuntimeException {
public ForbiddenRequestException(String message) {
super(message);
}
}
至少通过在属性中设置trace
来从JSON中删除server.error.include-stacktrace=never
,这可能不是理想的选择,但是我认为在生产中您还是应该这样做。