I've ErrorFactory class which based on error code creates an instance of different type of Errors. Also I have Output class which might contains one of those error types.
Code below shows how I am trying to use it, but unfortunately getting error. Could you please help me figure out what is wrong there and suggest better design. Thanks for any help!
OutputLike output = new OutputLike();
ErrorFactory errorFactory = new ErrorFactory();
int errorCode = ((Long)error.get("error_code")).intValue();
output.setError(errorFactory.<Error>getError(errorCode, error));
Error:(97, 27) java: method setError in class com.electronsoftware.VKLiker.responseoutput.output.Output<T> cannot be applied to given types;
required: com.electronsoftware.VKLiker.error.Error
found: java.lang.Object
reason: actual argument java.lang.Object cannot be converted to com.electronsoftware.VKLiker.error.Error by method invocation conversion
======
public class ErrorFactory <T extends Error> {
public <T> T getError(int error_code, JSONObject errorBody){
Error.ErrorType errorType = Error.ErrorType.values()[error_code];
switch(errorType){
case CAPTCHA_NEEDED:{
return (T) Parser.parseCaptchaRequiredError(errorBody);
}
case USER_AUTHORIZATION_FAILED:{
break;
}
case TOO_MANY_REQUESTS:{
break;
}
case NOT_ENOUGH_PERMISSIONS:{
break;
}
case UNKNOWN:{
break;
}
}
return null;
}
}
====
public class OutputLike <E extends Error> extends Output <E> {
....
}
public abstract class Output <T extends Error> {
private boolean isError;
private T error;
public boolean isError(){
return this.isError;
}
public T getError(){
return this.error;
}
public void setError(T error){
this.error = error;
}
}
====
public static ErrorCaptchaRequired parseCaptchaRequiredError(JSONObject error){
ErrorCaptchaRequired captchaError = null;
....
captchaError = new ErrorCaptchaRequired(msg, captchaId, captchaUrl);
return captchaError;
}
====
public class ErrorCaptchaRequired extends Error {
........
}
Errors are serious problems that can result in an unstable JVM, such as an OutOfMemoryError. These should beExceptions, notErrors. Developers should never catchErrors unless there is a fantastically good reason for doing so.getErrorshould just returnError. You should also heed the advice given by @JonK aboutErrorvs.Exception.