不得不说,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
return@onErrorResume 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))
}
}
}