以下是该方案: 我创建了以下自定义响应异常,以触发401 Http状态:
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public class HttpUnauthorizedException extends RuntimeException {
}
使用例外的控制器:
@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();
}
}
...
}
现在,当我尝试访问控制器以查看401异常时,服务器会激活Http错误代码500。但有趣的是,当我尝试使用HttpStatus.NOT_FOUND
它实际上有效时,服务器会激活404.这里有什么我不知道的吗?
提前致谢: - )
答案 0 :(得分:4)
首先throw new HttpUnauthorizedException();
然后您可以在具有@ControllerAdvice
注释
@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;
}
}
答案 1 :(得分:0)
我认为代码应该简单得多,也许答案是用旧的Spring版本编写的。
在此示例中,我实现了用于处理异常的方法- HttpClientErrorException.Unauthorized 以解决身份验证问题(401):
@ControllerAdvice
public class MyErrorsHandler extends ResponseEntityExceptionHandler
{
@ExceptionHandler(HttpClientErrorException.Unauthorized.class)
protected ResponseEntity<Object> handleAuthenticationError(RuntimeException ex, WebRequest request)
{
return handleExceptionInternal(ex,
"Cannot login, please check your inputs",
new HttpHeaders(), HttpStatus.UNAUTHORIZED, request);
}
}
最后我得到正确的GUI错误