提问人:vitalii 提问时间:8/29/2023 最后编辑:Robertvitalii 更新时间:8/30/2023 访问量:56
为什么我的自定义异常处理程序未捕获 AuthenticationException?
Why AuthenticationException is not caught by my custom exception handler?
问:
捕获异常的处理程序和方法如下所示:
@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(AuthenticationException.class)
public ResponseEntity<ErrorResponse> authenticationException(AuthenticationException ex) {
ErrorResponse errorResponse = new ErrorResponse(
HttpStatus.UNAUTHORIZED.value(),
List.of(ex.getMessage()),
LocalDateTime.now()
);
return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
}
}
和例外:
org.vitaliistf.twowheels4u.exception.AuthenticationException: JWT expired or invalid
at org.vitaliistf.twowheels4u.security.jwt.JwtTokenService.validateToken(JwtTokenService.java:94) ~[classes/:na]
...
Caused by: io.jsonwebtoken.MalformedJwtException: Unable to read JSON value: z�alg":"HS256"}
at io.jsonwebtoken.impl.DefaultJwtParser.readValue(DefaultJwtParser.java:554) ~[jjwt-0.9.1.jar:0.9.1]
...
Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'z': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
at [Source: (String)"z�alg":"HS256"}"; line: 1, column: 2]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:2477) ~[jackson-core-2.15.2.jar:2.15.2]
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:760) ~[jackson-core-2.15.2.jar:2.15.2]
...
我什至试图改变方法只是为了捕捉,但它不起作用。我希望在客户端上从此方法收到错误响应(json),但收到html错误页面以及状态500。Exception.class
答:
0赞
Gaurav
8/30/2023
#1
一旦 Spring Security 完成对请求的身份验证和授权,您的处理程序就会发挥作用 - 即当控制权掌握在 MVC HandlerMapping 手中时。AuthenticationException.class
您必须向 Spring Security Config 提供 to be handle 的实现才能处理它。AuthenticationFailureHandler
AuthenticationException
评论
AuthenticationException
org.springframework.security.core.AuthenticationException
org.vitaliistf.twowheels4u.exception.AuthenticationException