我想得到一个例外的消息"密码不正确"。
这是我曾经尝试过的:
@PostMapping("/login")
public ResponseEntity<Object> login(@RequestBody CustomUserDetails user) {
UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());
if (userDetails == null || !passwordEncoder.matches(user.getPassword(), userDetails.getPassword())) {
throw new CustomAuthenticationException("Password is not correct");
}
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = jwt.generateToken(user);
return ResponseEntity.ok(token);
}
public class CustomAuthenticationException extends AuthenticationException {
public CustomAuthenticationException(String msg) {
super(msg);
}
}
@RestControllerAdvice
public class AuthControllerAdvice extends ResponseEntityExceptionHandler {
@ExceptionHandler(PSQLException.class)
public ResponseEntity<ErrorResponse> handlePSQLException() {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, LocalDateTime.now(), "User already exists");
return ResponseEntity.internalServerError().body(errorResponse);
}
@ExceptionHandler(AuthenticationException.class)
public ResponseEntity<Object> handleBadCredentialsException() {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST, LocalDateTime.now(), "Invalid username or password");
return ResponseEntity.badRequest().body(errorResponse);
}
}
如果密码不正确,客户端将收到以下响应:
{
"status": "BAD_REQUEST",
"timestamp": "28.02.2023, 11:06:14",
"message": "Invalid username or password"
}
这是错误的消息。我期望的是throw new CustomAuthenticationException("Password is not correct");
。当我运行调试模式时,该行将被执行,但它没有返回任何东西。
2条答案
按热度按时间jbose2ul1#
这是正确的行为,因为类CustomAuthenticationException扩展了AuthenticationException。并且只为超类AuthenticationException定义了异常处理程序。
请为您的自定义异常添加另一个处理程序。类似于:
oknwwptz2#
你可以试试看。