Вы можете реализовать так:
Я предполагаю, что categoriesService.addNewCategory
возвращает _id
, null или выдает Exception
@PostMapping("/v1/cat")
public Mono<ResponseEntity<ResponseDto<String>>> createCategory(@RequestBody Categories services) throws Exception {
return Mono
.just(services)
.map(categoriesService::addNewCategory)
.map(result -> new ResponseEntity<>(ResponseDto.success(result), HttpStatus.OK))
//Couldn't reproduce
//.defaultIfEmpty(new ResponseEntity<>(ResponseDto.fail("not found", String.class), HttpStatus.BAD_REQUEST))
.onErrorResume(
throwable -> Mono.just(new ResponseEntity<>(ResponseDto.fail(throwable.getMessage(),
String.class), HttpStatus.BAD_REQUEST)));
}
{
"success": true,
"data": "5f09f5ac102c3c32c4203d8c",
"error": null
}
При ошибке
{
"success": false,
"data": null,
"error": "Cat4 already exists"
}
ResponseDto класс
public class ResponseDto<T> {
private Boolean success;
private T data;
private String error;
private ResponseDto(Boolean success, T data, String error) {
this.success = success;
this.data = data;
this.error = error;
}
public static <T> ResponseDto<T> success(T data) {
return new ResponseDto<T>(true, data, null);
}
@SuppressWarnings("unchecked")
public static <T, S> ResponseDto<T> fail(String error, S clazz) {
return (ResponseDto<T>) new ResponseDto<S>(false, null, error);
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}