filtering(@Valid @RequestBody MyRequest" /> filtering(@Valid @RequestBody MyRequest" /> filtering(@Valid @RequestBody MyRequest"/>

Why my controller advice does not work properly with Mono?

40 views Asked by At

I have controller like this:

    @PostMapping(consumes = "application/json", value = "id")
    public Mono<MyResponse> filtering(@Valid @RequestBody MyRequest request) {
        return Mono.fromCallable(() ->peopleFiltering.filter(
                        request.getEntity()))
                .flatMap(result -> result.map(MyResponseMapper::mapToResponse));
}

And this is my controller advice:

@ControllerAdvice
   public class CustomExceptionHandler {`

    @ExceptionHandler({NotFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public Mono<BankFilteringError> handleNotFound(NotFoundException ex) {
        MyError error = new MyError();
        error.setCode("404");
        error.setDescription("404 NOT_FOUND");
       error.setInstance("instance");
       error.setMessage("Not Found");

       return Mono.just(error);
    }

    @ExceptionHandler({BadRequestException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public BankFilteringError handleBadRequest(BadRequestException ex) {
        MyError error = new MyError();
        error.setCode("400");
        error.setDescription("Invalid Request Body");
        error.setInstance("instance");
        error.setMessage("Bad Request"); // Include the specific error message
        return error;
    }
  }

These are my custom exception classes:

public class NotFoundException extends RuntimeException {
    public NotFoundException(String errorMessage) {
        super(errorMessage);
    }
}

and

public class BadRequestException extends RuntimeException {
    public BadRequestException(String message) {
        super(message);
    }
}

But when I hit my url in postman I am getting 404 and 400 without my body.

I tried with

.switchIfEmpty(Mono.error(request.gEntity() == null ?
                        new BadRequestException("Invalid Request Body") :
                        new NotFoundException("Not Found")));

But without luck. Only time when this worked is when I put

@ExceptionHandler({RunTimeException.class}) //so, not my class
   @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public BankFilteringError handleBadRequest(BadRequestException ex) {
        MyError error = new MyError();
        error.setCode("400");
        error.setDescription("Invalid Request Body");
        error.setInstance("instance");
        error.setMessage("Bad Request"); // Include the specific error message
        return error;
    }
  }

But otherwise getting default spring errors 400 and 404 without my body. What am I doing wrong?

0

There are 0 answers