Giriş
Eğer WebFlux kullanmıyorsak, ResponseEntityExceptionHandler yazısına bakabiliriz.
Elimizde şöyle bir kod olsun
public class FormatNameRequest {@NotNull(message = "Title cannot be null")private String title;@NotNull@Size(message = "First name must be between 2 and 25 characters", min = 2, max = 25)private String firstName;private String middleName;@NotBlank(message = "Last name cannot be empty")private String lastName;...}
Şöyle yaparız. Burada @Valid anotasyonundan sonra, post edilen parametre Mono<...> şeklinde kodlanıyor
Test için şöyle yaparız@RestControllerpublic class ValidationDemoController {@PostMapping("/format")public Mono<ResponseEntity<FormattedNameResponse>> format(@Valid @RequestBody
Mono<FormatNameRequest> request) {return request.map(res -> ResponseEntity.status(HttpStatus.OK).body(alo
FormattedNameResponseMapper.fromFormatNameRequest(res))).onErrorResume(WebExchangeBindException.class,ex -> Mono.just(ResponseEntity.status(HttpStatus.BAD_REQUEST).body(FormattedNameResponseMapper.fromWebExchangeBindException(ex))));}}public class FormattedNameResponseMapper {public static FormattedNameResponse fromWebExchangeBindException(
WebExchangeBindException ex) {FormattedNameResponse res = new FormattedNameResponse();List<Error> errors = ex.getFieldErrors().stream().map(fieldError -> new Error(fieldError.getField(), fieldError.getDefaultMessage())).collect(Collectors.toList());res.setErrors(errors);return res;}public static FormattedNameResponse fromFormatNameRequest(FormatNameRequest req) {String s = String.format("%s %s %s %s", req.getTitle(), req.getFirstName(),
req.getMiddleName(), req.getLastName());FormattedNameResponse res = new FormattedNameResponse();res.setFormattedName(s);return res;}}
RequestPOST http://host:port/formatContent-Type: application/json{"title":"Mr","firstName":"Jhon","middleName": "Martin","lastName": "Smith"}Succesful Response200 OKContent-Type: application/json{"formattedName": "Mr Jhon Martin Smith"}Error Response400 Bad RequestContent-Type: application/json{"errors": [{"code": "erroCode1","message": "errorMessage1"},{"code": "erroCode2","message": "errorMessage2"},{"code": "erroCode3","message": "errorMessage13"}]}
Hiç yorum yok:
Yorum Gönder