gpt4 book ai didi

java - Spring AccessDeniedException 中的自定义消息

转载 作者:行者123 更新时间:2023-11-29 04:05:17 24 4
gpt4 key购买 nike

在我的 Spring Boot Web 应用程序中,只要用户没有必要的权限,我就会在我的业务代码中抛出 org.springframework.security.access.AccessDeniedExceptionAccessDeniedException 的优点是 Spring 会自动调用 AuthenticationEntryPoint 等。

但是,我正在使用自定义异常消息来指示异常的确切原因(例如 throw new AccessDeniedException("You do not have permissions to do XYZ"),但在生成的 JSON 中响应消息总是“拒绝访问”,例如:

{
"timestamp": "2019-12-12T10:01:10.342+0000",
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/myurl"
}

深入研究 Spring 的代码(DefaultErrorAttributes 方法 addErrorDetails)揭示了消息是从 1) 异常消息 2) 请求属性 javax 构建的。 servlet.error.message,第二个覆盖第一个。

有人知道为什么请求属性优先于异常消息吗?

有没有一种简单的方法可以在 Spring Boot 错误响应中显示自定义异常消息?我想保留默认的 Spring Boot 错误响应,但在“消息”字段中使用我的自定义消息,理想情况下我希望 Spring Boot 构造 JSON 对象的其余部分(即时间戳、状态等)。最终结果应如下所示:

{
"timestamp": "2019-12-12T10:01:10.342+0000",
"status": 403,
"error": "Forbidden",
"message": "You do not have permissions to do XYZ",
"path": "/myurl"
}

这确实适用于其他类型的异常。只是 AccessDeniedException 似乎是一个特例。 AccessDeniedException 是否可能不是此请求的正确选择(尽管 javadoc 表明它是)?

最佳答案

您可以使用 Spring ControllerAdvice并使用 HttpServletResponse 发送自定义错误:

@ControllerAdvice
class AccessDeniedExceptionHandler {

@ExceptionHandler(value = AccessDeniedException.class)
public void handleConflict(HttpServletResponse response) throws IOException {
response.sendError(403, "Your Message");
}
}

这将返回:

{
"timestamp": 1576248996366,
"status": 403,
"error": "Forbidden",
"message": "Your Message",
"path": "/foo/bar"
}

通过这种方式,您可以全局捕获特定类型的所有异常,并使您的 Controller 返回指定的自定义值。你也可以这样做,例如对于任何 IOException 并返回 404 Not Found ResponseEntity 以及您指定的消息。

关于java - Spring AccessDeniedException 中的自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59302621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com