Spring Boot 客户端收到错误的异常消息

c86crjj0  于 2023-03-02  发布在  Spring
关注(0)|答案(2)|浏览(162)

我想得到一个例外的消息"密码不正确"。
这是我曾经尝试过的:

@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");。当我运行调试模式时,该行将被执行,但它没有返回任何东西。

jbose2ul

jbose2ul1#

这是正确的行为,因为类CustomAuthenticationException扩展了AuthenticationException。并且只为超类AuthenticationException定义了异常处理程序。
请为您的自定义异常添加另一个处理程序。类似于:

@ExceptionHandler(CustomAuthenticationException.class)
public ResponseEntity<Object> handleBadCredentialsException(Exception exception) {
    ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST, LocalDateTime.now(), exception.getMessage());
    return ResponseEntity.badRequest().body(errorResponse);
}
oknwwptz

oknwwptz2#

你可以试试看。

@ExceptionHandler(AuthenticationException.class)
public ResponseEntity<Object> handleBadCredentialsException(AuthenticationException exception) {
    ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST, LocalDateTime.now(), exception.getMessage());
    return ResponseEntity.badRequest().body(errorResponse);
}

相关问题