# HttpException - Way to deal with Error Codes
###### tags: `Android Code Sample`

[TOC]
# Error Code
Can use [@IntDef](/cCkssEPkTqiSlhjbOvMX9A) to state all Error Codes, and by using annotation, we can make development much more readable and get a note on errors right away in the process.
# Error Exception Factory
We can make a factory and deal all errors here. In order to have a widely used Exception as return, we have to make a class, in this case **HttpException**.
## **Our own HttpException Class:**
```java=
public class HttpException {
private int code;
private String displayMsg;
private Throwable throwable;
public HttpException(Throwable e) { throwable = e; }
public HttpException(Throwable throwable, int code, String displayMsg){
this.throwable = throwable;
this.displayMsg = displayMsg;
this.code = code;
}
//Setter
public void setCode(int code) {
this.code = code;
}
public void setDisplayMsg(String displayMsg) {
this.displayMsg = displayMsg;
}
//Getter
public int getCode() {
return code;
}
public String getDisplayMsg() {
return displayMsg;
}
}
```
## **ExceptionFactory Example:**
**CodeException** is a class made with @IntDef. (For more can check Error Code Section).
```java=
import org.json.JSONException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
public class ExceptionFactory {
private static final String HTTP_EXCEPTION_ERROR = "Network Error";
private static final String CONNECTION_ERROR = "Connection Error";
private static final String JSON_ERROR = "Fail to parse data";
private static final String UNKNOWN_HOST_ERROR = "Recheck your network status";
public static HttpException checkException(Throwable e){
HttpException dealException = new HttpException(e);
if (e instanceof RuntimeException) {
RuntimeException exception = (RuntimeException) e;
dealException.setCode(CodeException.RUNTIME_ERROR);
dealException.setDisplayMsg(exception.getMessage());
} else if (e instanceof ConnectException ||e instanceof SocketTimeoutException) {
dealException.setCode(CodeException.HTTP_ERROR);
dealException.setDisplayMsg(CONNECTION_ERROR);
} else if (e instanceof JSONException) { // || e instanceof ParseException (part of runtimeException
dealException.setCode(CodeException.JSON_ERROR);
dealException.setDisplayMsg(JSON_ERROR);
}else if (e instanceof UnknownHostException){
dealException.setCode(CodeException.UNKNOWN_HOST_ERROR);
dealException.setDisplayMsg(UNKNOWN_HOST_ERROR);
}else if(e != null){ // instanceof Throwable
dealException.setCode(CodeException.OTHER_ERROR);
dealException.setDisplayMsg(e.getMessage());
}else {
dealException.setCode(CodeException.NETWORK_ERROR);
dealException.setDisplayMsg(HTTP_EXCEPTION_ERROR);
}
return dealException;
}
}
```
## Factory usage display
```java=
@Override
public void onError(Throwable e) {
e.printStackTrace();
onError(FactoryException.checkException(e));
}
```