You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

抛出CustomAuthenticationException后客户端未收到指定异常消息求助

问题解决方法

你的问题出在全局异常处理器的匹配逻辑和消息硬编码上,具体修正步骤如下:

1. 为自定义异常添加专属处理器

Spring的@ExceptionHandler会优先匹配最具体的异常类型,所以需要给CustomAuthenticationException单独编写处理器,避免被父类AuthenticationException的处理器覆盖。

2. 从异常实例中获取自定义消息

原来的处理器方法没有接收异常参数,而是硬编码了错误消息,导致无法获取你抛出的CustomAuthenticationException中的自定义文本,需要在方法参数中传入异常并调用getMessage()获取内容。

修改后的全局异常处理器代码

@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(CustomAuthenticationException.class)
    public ResponseEntity<Object> handleCustomAuthenticationException(CustomAuthenticationException ex) {
        ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST, LocalDateTime.now(), ex.getMessage());
        return ResponseEntity.badRequest().body(errorResponse);
    }

    // 处理其他通用认证异常(可选,根据需求调整消息)
    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity<Object> handleAuthenticationException(AuthenticationException ex) {
        ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST, LocalDateTime.now(), ex.getMessage());
        return ResponseEntity.badRequest().body(errorResponse);
    }
}

原理说明

  • 当你抛出CustomAuthenticationException("Password is not correct")时,Spring会优先匹配@ExceptionHandler(CustomAuthenticationException.class)这个处理器,而不是父类的处理器。
  • 通过ex.getMessage()可以直接获取你在抛出异常时传入的自定义消息,替换原来的硬编码文本。

内容的提问来源于stack exchange,提问作者Reem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 11:38:52