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

前端 未结 6 2057
轮回少年
轮回少年 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:45

    A quick way to map your exceptions to http response status is to throw org.springframework.web.server.ResponseStatusException / or create your own subclasses...

    Full control over http response status + spring will add a response body with the option to add a reason.

    In Kotlin it could look as simple as

    @Component
    class MyHandler(private val myRepository: MyRepository) {
    
        fun getById(req: ServerRequest) = req.pathVariable("id").toMono()
                .map { id -> uuidFromString(id) }  // throws ResponseStatusException
                .flatMap { id -> noteRepository.findById(id) }
                .flatMap { entity -> ok().json().body(entity.toMono()) }
                .switchIfEmpty(notFound().build())  // produces 404 if not found
    
    }
    
    fun uuidFromString(id: String?) = try { UUID.fromString(id) } catch (e: Throwable) { throw BadRequestStatusException(e.localizedMessage) }
    
    class BadRequestStatusException(reason: String) : ResponseStatusException(HttpStatus.BAD_REQUEST, reason)
    

    Response Body:

    {
        "timestamp": 1529138182607,
        "path": "/api/notes/f7b.491bc-5c86-4fe6-9ad7-111",
        "status": 400,
        "error": "Bad Request",
        "message": "For input string: \"f7b.491bc\""
    }
    

提交回复
热议问题