How to return 404 with Spring WebFlux

前端 未结 3 1923
無奈伤痛
無奈伤痛 2021-02-15 23:47

I\'m having a controller like this one (in Kotlin):

@RestController
@RequestMapping(\"/\")
class CustomerController (private val service: CustomerService) {
             


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-16 00:11

    You can use ResponseStatusException, just extend your exception:

    public class YourLogicException extends ResponseStatusException {
    
    public YourLogicException(String message) {
        super(HttpStatus.NOT_FOUND, message);
    }
    
    public YourLogicException(String message, Throwable cause) {
        super(HttpStatus.NOT_FOUND, message, cause);
    }
    

    And in service:

    public Mono doLogic(Mono ctx) {
        return ctx.map(ctx -> doSomething(ctx));
    }
    
    private String doSomething(YourContext ctx) {
        try {
            // some logic
        } catch (Exception e) {
            throw new YourLogicException("Exception message", e);
        }
    }
    

    And after that, you could have a pretty message:

     { "timestamp": 00000000, "path": "/endpoint", "status": 404, "error": "Not found", "message": "Exception message" }
    

提交回复
热议问题