gpt4 book ai didi

java - 抛出 HttpStatus.UNAUTHORIZED 的 Spring Controller 会触发 500 Http 错误而不是 401

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:14:42 25 4
gpt4 key购买 nike

场景如下:我创建了以下自定义响应异常,以触发 401 Http 状态:

@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public class HttpUnauthorizedException extends RuntimeException {

}

使用异常的 Controller :

@Controller
public UserController {
@RequestMapping(value = "api/user")
@ResponseBody

public String doLogin(
@RequestParam(value = "username", required = false) String username, @RequestParam(value = "password", required = false) String password) {
if(userLoggedIn(String username, String password)) {
return "OK";
}
else {
throw new HttpUnauthorizedException();
}
}
...
}

现在,当我尝试访问 Controller 以查看 401 异常时,服务器改为触发 Http 错误代码 500。但有趣的是,当我尝试使用 HttpStatus.NOT_FOUND 它确实有效时,服务器触发 404。我在这里遗漏了什么吗?

提前致谢:-)

最佳答案

首先 throw new HttpUnauthorizedException();

然后你可以在一个有@ControllerAdvice注解的普通 Controller 上捕获它

@ControllerAdvice // To Handle Exceptions
public class ExceptionController {
//// ...........

@ExceptionHandler({HttpUnauthorizedException.class})
@ResponseBody
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
Map<String, String> unauthorizedAccess(Exception e) {
Map<String, String> exception = new HashMap<String, String>();

log.error("unauthorized Access to the API: " + e.getMessage(), e);
exception.put("code", "401");
exception.put("reason", e.getMessage());

return exception;
}
}

关于java - 抛出 HttpStatus.UNAUTHORIZED 的 Spring Controller 会触发 500 Http 错误而不是 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22296448/

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