抛出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
相关产品推荐
相关产品推荐

