gpt4 book ai didi

design-patterns - 使用异常处理身份验证/授权错误是一种好习惯吗?

转载 作者:行者123 更新时间:2023-12-04 19:13:51 25 4
gpt4 key购买 nike

如果应用程序发现用户没有经过身份验证/授权做某事,那是不是出乎意料?

try {
if (notAuth())
throw new UnAuthException();
} catch (UnAuthException e) {
Log . error(e);
return false;
}

如果是预期案例 ,那么为什么有这么多框架都有自己的 UnAuthException如果验证失败也不异常(exception)?

最佳答案

取决于范围。

业务逻辑 层“用户未授权/认证”的情况是异常的,应该会导致运行时异常,例如(Java代码):

public String salutation(User user) {
// may lead to a runtime exception if user is not authorized
return String.format("Hello, %s!", user.getName());
}
User的实现(当然是一个接口(interface))要么返回用户名,要么抛出 NonAuthenticatedExceptiongetName() .

门禁层用户授权/认证状态作为任何其他正常状态处理,不应视为异常情况,例如:
if (!user.isAuthenticated()) {
httpResponse.addHeader("WWW-Authenticate", "Basic realm=\"secure content\"");
}

关于design-patterns - 使用异常处理身份验证/授权错误是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12336972/

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