Quantcast
Channel: User Chris - Stack Overflow
Viewing all articles
Browse latest Browse all 41

How to return validation error messages with Springboot WebFlux

$
0
0

How do I return the custom validation errors for Springboot 3.0 with WebFlux?

I have wired up the following controller

import jakarta.validation.Valid;//...@Validated@RestController@RequestMapping("/organizations")@RequiredArgsConstructorpublic class OrganizationController {    private final OrganizationService organizationService;    @PostMapping("/create")    public Mono<ResponseEntity<Organization>> create(@Valid @RequestBody final OrganizationDto organizationDto) {        return organizationService.create(organizationDto).map(ResponseEntity::ok);    }}

The OrganizationDto has been setup as:

import jakarta.validation.constraints.NotNull;//...@Data@Builder@AllArgsConstructor@NoArgsConstructorpublic final class OrganizationDto {    @NotNull        private String name;    //...}

And finally I have what I thought was a correct ValidationHandler/ErrorController

@Slf4j@ControllerAdvice@RequiredArgsConstructorpublic class ErrorController {    @ResponseBody    @ExceptionHandler(MethodArgumentNotValidException.class)    @ResponseStatus(HttpStatus.BAD_REQUEST)    public Map<String, String> handleValidationExceptions(final MethodArgumentNotValidException ex) {        final BindingResult bindingResult = ex.getBindingResult();        final List<FieldError> fieldErrors = bindingResult.getFieldErrors();        final Map<String, String> errors = new HashMap<>();        fieldErrors.forEach(error -> errors.put(error.getField(), error.getDefaultMessage()));        return errors;    }}

However if I send a payload to the endpoint in the controller of

{"name": null}

I get back

{"timestamp": 1677430410704,"path": "/organizations/create","status": 400,"error": "Bad Request","requestId": "2050221b-2"}

Which is almost what I want, but I'm trying to get the reason why it failed validation into the response but not having any luck

I've put breakpoints on the handleValidationExceptions but looks like I'm never getting into it, and I'm also not seeing anything in the server side logs which points to whats going on.

I do have org.springframework.boot:spring-boot-starter-validation on my classpath, and I'm using the latest Springboot 3.0.3

Have I missed a step or annotation here?


Viewing all articles
Browse latest Browse all 41

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>