My Java application needs to serialize/deserialize an XML structure received via HTTP. This XML message may contain an Error element on almost any level of the XML. That’s why all classes extend ApiError. Please see the following question as well: Deserialize repeating XML elements in Simple 2.5.3 (Java)
I have created the following class:
public class ApiError {
private String code;
private String level;
private String text;
public get/set...() {}
}
Almost every other class in my application extends the ApiError class as those classes may raise an error.
I’d like to have a method like getErrorOrigin() which returns the name of the class which first created an instance of ApiError?
Is there an easy way in Java how to do this?
Thanks,
Robert
Yes, you can do this, by getting the stack trace of the current thread in the
ApiErrorconstructor:You can see why this works by putting
in the
ApiErrorconstructor. If you create a new instance ofApiError, you’ll see a stack trace that looks like this:Thread.currentThread().getStackTrace()will give you an array ofStackTraceElementobjects:getStackTrace()method itself, which is executing when the trace is generated.ApiErrorconstructor, which calledgetStackTrace().2) – is for the method that called theApiErrorconstructor. By callinggetClassName()on that element, you get the name of the class containing the method that invoked theApiErrorconstructor.Having said all that, it seems you’re trying to reimplement exceptions. I would seriously consider throwing exceptions from your methods, rather than returning
ApiErrorobjects. This keeps the error handling separate from your ‘business logic’. Also errors are (hopefully) an exceptional situation, so it makes sense to use exceptions for error handling, rather than havingApiErrorpollute your class hierarchy.