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

Kotlin Spring Webflux中@ControllerAdvice异常处理不生效求助

Kotlin Spring Boot Webflux 自定义异常响应无法正常返回

我正在开发一个简单的Kotlin Spring Boot Webflux应用,添加异常处理后,无论怎么尝试都无法正常显示自定义错误信息。在IntelliJ调试模式下,可以确认代码确实进入了@ControllerAdvice类,自定义错误对象也被正确填充,但该对象就是无法作为响应返回。用Insomnia测试时,无法收到预期的自定义错误内容。

当我把自定义错误数据类替换成String类型时,能正常返回预期的字符串信息,因此问题大概率出在自定义错误类AppError上。

Controller代码

@RestController
@RequestMapping("/api")
class AppUserController(private val appUserService: AppUserService) {
   @PostMapping("/users")
    @ResponseStatus(HttpStatus.CREATED)
    fun addUser(@Valid @RequestBody appUserRequest: AppUserRequest): Mono<AppUserRequest> =
        appUserService.addUser(appUserRequest)
}

Service代码

@Service
class AppUserServiceImpl(private val appUserRepository: AppUserRepository): AppUserService {
override fun addUser(appUserRequest: AppUserRequest): Mono<AppUserRequest> {
        val appUser: AppUser = toEntity(appUserRequest)
        val userEmail: String = appUser.email

        return appUserRepository.findByEmail(userEmail)
            .flatMap<AppUserRequest> { Mono.error(BadRequestException("User with email $userEmail already exists.")) }
            .switchIfEmpty(appUserRepository.save(appUser)
                               .map { savedAppUser -> toApi(savedAppUser) }
                               .log("New app user has been added"))
    }
}

全局异常处理类代码

@ControllerAdvice
class ExceptionControllerAdvice {

    @ExceptionHandler(BadRequestException::class)
    fun handleBadRequestException(exception: BadRequestException): ResponseEntity<AppError> {

        val errorMessage = AppError(HttpStatus.BAD_REQUEST.value(),
                                    HttpStatus.BAD_REQUEST.reasonPhrase,
                                    Instant.now(),
                                    exception.localizedMessage)
        return ResponseEntity(errorMessage, HttpStatus.BAD_REQUEST)
    }
}

自定义错误数据类AppError

data class AppError(private var errorCode: Int?,
               private var status: String?,
               @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'hh:mm:ssZ", timezone = "Europe/London")
               private val timestamp: Instant,
               private var message: String?) 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:32:44