如何使用onErrorMap()处理异常时如何访问Mono <T>?

在我定义的数据类中, 'name'在整个mongo集合中必须是唯一的:

@Document data class Inn(@Indexed(unique = true) val name: String, val description: String) { @Id var id: String = UUID.randomUUID().toString() var intro: String = "" } 

所以在服务中,如果有人再次传递相同的名字,我必须捕获意外的异常。

 @Service class InnService(val repository: InnRepository) { fun create(inn: Mono<Inn>): Mono<Inn> = repository .create(inn) .onErrorMap( DuplicateKeyException::class.java, { err -> InnAlreadyExistedException("The inn already existed", err) } ) } 

这是好的,但如果我想添加更多的信息,如"The inn named '$it.name' already existed" ,我应该怎么做转化异常与丰富的消息。

显然,将Mono<Inn>分配给本地变量并不是一个好主意。

在处理程序类似的情况,我想给客户更多的信息,从定制的异常派生,但没有找到适当的方式。

 @Component class InnHandler(val innService: InnService) { fun create(req: ServerRequest): Mono<ServerResponse> { return innService .create(req.bodyToMono<Inn>()) .flatMap { created(URI.create("/api/inns/${it.id}")) .contentType(MediaType.APPLICATION_JSON_UTF8).body(it.toMono()) } .onErrorReturn( InnAlreadyExistedException::class.java, badRequest().body(mapOf("code" to "SF400", "message" to t.message).toMono()).block() ) } } 

在reactor中 ,你不会在onErrorMap把你想要的值交给你作为参数,你只是得到了Throwable 。 但是,在Kotlin中,您可以到达错误处理程序的范围之外,并直接引用inn 。 你不需要改变很多:

 fun create(inn: Mono<Inn>): Mono<Inn> = repository .create(inn) .onErrorMap( DuplicateKeyException::class.java, { InnAlreadyExistedException("The inn ${inn.name} already existed", it) } ) }