Created
November 18, 2023 19:48
-
-
Save emmysteven/232559d2fd4f199d4d8d0ae954ede806 to your computer and use it in GitHub Desktop.
ServiceResponse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.core.JsonProcessingException; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import lombok.Data; | |
import org.springframework.validation.ObjectError; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Map; | |
@Data | |
public class ServiceResponse<T> { | |
private final List<ObjectError> validationErrors = new ArrayList<>(); | |
private T data; | |
private String message; | |
// Getters and setters | |
public List<String> getErrorMessages() { | |
List<String> result = new ArrayList<>(); | |
for (ObjectError error : validationErrors) { | |
result.add(error.getDefaultMessage()); | |
} | |
return result.isEmpty() ? null : result; | |
} | |
public List<String> getModelStateErrors(Map<String, List<ObjectError>> modelState) { | |
List<String> result = new ArrayList<>(); | |
for (List<ObjectError> errors : modelState.values()) { | |
for (ObjectError error : errors) { | |
result.add(error.getDefaultMessage()); | |
} | |
} | |
return result.isEmpty() ? null : result; | |
} | |
public boolean hasError() { | |
return !validationErrors.isEmpty(); | |
} | |
public void addError(String error) { | |
validationErrors.add(new ObjectError("", error)); | |
} | |
public void addError(ObjectError validationResult) { | |
validationErrors.add(validationResult); | |
} | |
public void addError(List<ObjectError> validationResults) { | |
validationErrors.addAll(validationResults); | |
} | |
@Override | |
public String toString() { | |
ObjectMapper mapper = new ObjectMapper(); | |
try { | |
return mapper.writeValueAsString(this); | |
} catch (JsonProcessingException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment