1

I want to write a file log with the errors of a method that reads from a xml file. This method is too large, and I want to control the line content that causes an error. Now I have a variable that has the field I'll going to read and If this field fails the method return the error with this field's name. It's a bad solution, and I need something similar but more dynamic.

String error;
...
error= name;
String name = getValue("name");
error= surname;
String surname = getValue("surname");

......

catch(Exception){
return error;
}
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Peluco
  • 75
  • 1
  • 10
  • Just propagate the exception to the caller. It contains the information needed, like the line number where it occurred. If you need more information use `throw new RuntimeException("some additional information", exception)` or any other exception type. – Tom Jun 25 '19 at 09:58

2 Answers2

1

Yes, it's a terrible idea.

You save "name" into the error variable prior to reading the property. You have no idea if the property will be read but the variable has been set regardless of the read. If every property has been parsed successfully, which is what we hope for, you still will have the error variable set to some property name.

In such scenarios, we usually put this information into an exception instance. When we are in a catch block, we are able to access that information and act accordingly.

public String getValue(String propertyName) {
    try {
        tryToReadProperty(propertyName);
    } catch (Exception e) {
        // something wrong happened
        throw new IllegalArgumentException(propertyName);
    }
}

...

try {
    String name = getValue("name");
    String surname = getValue("surname");
} catch (IllegalArgumentException e){
    String error = e.getMessage();
}

I used IllegalArgumentException for the sake of simplicity, it should be replaced with a more meaningful domain-specific exception type.

return error;

We rarely do that. Instead, we propagate an exception or rethrow a different layer-determined exception.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
0

See the Notification pattern by Martin Fowler.

esmiralha
  • 10,587
  • 1
  • 16
  • 20