From 9ac7a98257e26fbfff6296082a6be8ed6b4f8f75 Mon Sep 17 00:00:00 2001 From: Marc Baloup Date: Thu, 24 Aug 2023 12:40:38 +0200 Subject: [PATCH] SQLElement: better error handling of the get method + A nullable field that is not set will return null instead of throwing an exception. --- .../main/java/fr/pandacube/lib/db/SQLElement.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/pandalib-db/src/main/java/fr/pandacube/lib/db/SQLElement.java b/pandalib-db/src/main/java/fr/pandacube/lib/db/SQLElement.java index cae4a98..713f6b6 100644 --- a/pandalib-db/src/main/java/fr/pandacube/lib/db/SQLElement.java +++ b/pandalib-db/src/main/java/fr/pandacube/lib/db/SQLElement.java @@ -241,17 +241,24 @@ public abstract class SQLElement> { * Gets the value of the provided field in this entry. * @param field the field to get the value from. * @return the value of the provided field in this entry. + * @throws IllegalArgumentException if the provided field is null or not from the table represented by this class. + * @throws IllegalStateException if the field is not nullable and there is no value set * @param the Java type of the field. */ public T get(SQLField field) { - if (field == null) throw new IllegalArgumentException("field can't be null"); + if (field == null) + throw new IllegalArgumentException("field can't be null"); + if (!fields.containsKey(field.getName()) || !fields.get(field.getName()).equals(field)) + throw new IllegalArgumentException("The provided field " + field + " is not from this table " + getClass().getName()); if (values.containsKey(field)) { @SuppressWarnings("unchecked") T val = (T) values.get(field); return val; } - throw new IllegalArgumentException("The field '" + field.getName() + "' in this instance of " + getClass().getName() - + " does not exist or is not set"); + if (field.nullable) + return null; + throw new IllegalStateException("The non-nullable field '" + field.getName() + "' in this instance of " + getClass().getName() + + " is not set"); } /**