what is the right way to handle errors in spring-webflux

前端 未结 6 2059
轮回少年
轮回少年 2020-12-09 11:12

I\'ve been doing some research using spring-webflux and I like to understand what should be the right way to handle errors using Router Functions.

I\'ve created an s

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 11:41

    Why not do it the old fashioned way by throwing exceptions from handler functions and implementing your own WebExceptionHandler to catch 'em all:

    @Component
    class ExceptionHandler : WebExceptionHandler {
        override fun handle(exchange: ServerWebExchange?, ex: Throwable?): Mono {
            /* Handle different exceptions here */
            when(ex!!) {
                is NoSuchElementException -> exchange!!.response.statusCode = HttpStatus.NOT_FOUND
                is Exception -> exchange!!.response.statusCode = HttpStatus.INTERNAL_SERVER_ERROR
            }
    
            /* Do common thing like logging etc... */
    
            return Mono.empty()
        }
    }
    

    Above example is in Kotlin, since I just copy pasted it from a project I´m currently working on, and since the original question was not tagged for java anyway.

提交回复
热议问题