handle responses more properly

This commit is contained in:
Laurent
2025-03-16 16:18:39 +01:00
parent b273e73113
commit 401cda820c
4 changed files with 31 additions and 13 deletions

View File

@@ -1,5 +1,6 @@
package be.naaturel.letsmeet.controllers;
import be.naaturel.letsmeet.core.Result;
import be.naaturel.letsmeet.dto.httpRequest.EventDTO;
import be.naaturel.letsmeet.services.EventService;
import org.springframework.beans.factory.annotation.Autowired;
@@ -26,21 +27,20 @@ public class EventController {
} catch (Exception e){
return ResponseEntity
.internalServerError()
.build();
.body("An error has occured : " + e.getMessage());
}
}
@PostMapping({"/create", "/create/"})
public ResponseEntity<?> create(@RequestBody EventDTO dto){
try{
service.save(dto);
try {
Result<String> res = service.save(dto);
return ResponseEntity.ok(res);
} catch (Exception e){
return ResponseEntity
.internalServerError()
.build();
.body("An error has occured : " + e.getMessage());
}
return ResponseEntity.ok().build();
}
}

View File

@@ -0,0 +1,18 @@
package be.naaturel.letsmeet.core;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize
public class Result<T> {
private T value;
public Result(T value){
this.value = value;
}
public T getValue() {
return value;
}
}

View File

@@ -1,5 +1,6 @@
package be.naaturel.letsmeet.services;
import be.naaturel.letsmeet.core.Result;
import be.naaturel.letsmeet.mappers.Mapper;
public abstract class AbstractService<T, T_ENTITY, T_DTO> {
@@ -12,7 +13,7 @@ public abstract class AbstractService<T, T_ENTITY, T_DTO> {
this.requestMapper = requestMapper;
}
public abstract boolean save(T_DTO prop);
public abstract Result<?> save(T_DTO prop) throws Exception;
public abstract boolean delete(T_DTO prop);

View File

@@ -1,5 +1,6 @@
package be.naaturel.letsmeet.services;
import be.naaturel.letsmeet.core.Result;
import be.naaturel.letsmeet.dto.database.EventEntity;
import be.naaturel.letsmeet.dto.httpRequest.EventDTO;
import be.naaturel.letsmeet.mappers.database.EventMapper;
@@ -22,16 +23,14 @@ public class EventService extends AbstractService<Event, EventEntity, EventDTO>
}
@Override
public boolean save(EventDTO dto) {
public Result<String> save(EventDTO dto) throws Exception {
Event event = this.requestMapper.toModel(dto);
EventEntity entity = this.dataBaseMapper.toEntity(event);
try{
this.repo.save(entity);
return true;
} catch (IllegalArgumentException iae){
return false;
} catch (OptimisticLockingFailureException olfe){
return false;
return new Result<>(entity.token);
} catch (Exception e) {
throw new Exception("Something went wrong");
}
}