Last active
October 19, 2016 06:43
-
-
Save jsgao0/9c016b06d3fc6aa24e43fc2f6dd20f5e to your computer and use it in GitHub Desktop.
A custom Exception which is JSON-like.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import org.json.JSONObject; | |
public class ReturnException extends Exception { | |
// Because Exception implements Throwable which implements Serializable. | |
private static final long serialVersionUID = 1L; | |
public ReturnException(){} | |
// Use Exception constructor with JSON String is from getExceptionJSONString function includes retCode and retMessage. | |
public ReturnException(int retCode, String retMessage) { | |
super(getExceptionJSONString(retCode, retMessage)); | |
} | |
// Getter of retCode. | |
public int getRetCode() { | |
// Convert content of exception to be a JSON Object. | |
JSONObject jo = new JSONObject(this.getMessage()); | |
// Get retCode of the JSON Object as an integer and return. | |
return jo.getInt("retCode"); | |
} | |
// Getter of retMessage. | |
public String getRetMessage() { | |
JSONObject jo = new JSONObject(this.getMessage()); | |
return jo.getString("retMessage"); | |
} | |
// For constructor. | |
private static String getExceptionJSONString(int retCode, String retMessage) { | |
JSONObject jo = new JSONObject(); | |
jo.put("retCode", retCode); | |
jo.put("retMessage", retMessage); | |
return jo.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment