不得不说,spring的全局异常处理是真的麻烦

Spring

@Component
class WebExceptionHandle: ErrorWebExceptionHandler {
    override fun handle(exchange: ServerWebExchange, ex: Throwable): Mono<Void> {
        val response = exchange.response
        val headers = response.headers
        response.statusCode = HttpStatus.INTERNAL_SERVER_ERROR
        headers.contentType = MediaType.APPLICATION_JSON
        return response.writeAndFlushWith(Mono.just(ByteBufMono.just(response.bufferFactory().wrap(JSON.toJSONString(Result.failure<Unit>(ex.message)).toByteArray()))))
    }
}

@Component
@Order(0)
class Filter: WebFilter {
    override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
        return chain.filter(exchange).onErrorResume{
            val response = exchange.response
            val headers = response.headers
            response.statusCode = HttpStatus.INTERNAL_SERVER_ERROR
            headers.contentType = MediaType.APPLICATION_JSON
            [email protected] response.writeAndFlushWith(
                Mono.just(
                    ByteBufMono.just(
                        response.bufferFactory().wrap(JSON.toJSONString(Result.failure<Unit>(it.message)).toByteArray())
                    )
                )
            )
        }
    }
}

反正都得用ServerWebExchange来传递响应体。巨麻烦

Ktor

我用的是配置文件方式的,注册StatusPages插件即可

application.conf文件中ktor.application.modules中注册插件me.kuku.api.plugins.StatusPagesKt.statusPages,直接和路由一样的操作,使用call操作即可。要是Spring的异常处理也可以和路由一样的操作使用ServerResponse一样返回就好了

fun Application.statusPages() {
    install(StatusPages) {
        exception<Throwable> { cause ->
            call.respond(HttpStatusCode.InternalServerError, Result.failure(cause.message ?: "服务器内部错误", null))
        }
    }
}
最后修改:2021 年 12 月 31 日
如果觉得我的文章对你有用,请随意赞赏