可以使用枚舉類,也可以寫到配置文件中,再寫個工具類獲取.看項目需求了.
public enum ErrorCode {
OK(0,"OK"),ID_INVALID(1,"ID is invalid"),OTHER_ERR(2,"未知錯誤");
private int code;
private String message;
ErrorCode(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
@XmlRootElement//標識該資源可以被jersey轉為json或者xml
public class ErrorEntity {
private int resp_code;
private String resp_msg;
public ErrorEntity(int resp_code, String resp_msg) {
this.resp_code = resp_code;
this.resp_msg = resp_msg;
}
public ErrorEntity() {
}
public int getResp_code() {
return resp_code;
}
public void setResp_code(int resp_code) {
this.resp_code = resp_code;
}
public String getResp_msg() {
return resp_msg;
}
public void setResp_msg(String resp_msg) {
this.resp_msg = resp_msg;
}
}
public class DeviceException extends Exception {4.定義jersey異常處理器
private int code;
private String message;
/**
* 構造異常類
* @param code
* @param message
*/
public DeviceException( int code,String message) {
this.code = code;
this.message = message;
}
/**
* 根據枚舉類構造異常結果
* @param errorCode
*/
public DeviceException(ErrorCode errorCode) {
this.code = errorCode.getCode();
this.message = errorCode.getMessage();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
@Provider
public class DeviceExceptionMapper implements ExceptionMapper<Exception> {
@Override
public Response toResponse(Exception e) {
Response.ResponseBuilder ResponseBuilder = null;
if (e instanceof DeviceException){
//截取自定義類型
DeviceException exp = (DeviceException) e;
ErrorEntity entity = new ErrorEntity(exp.getCode(),exp.getMessage());
ResponseBuilder = Response.ok(entity, MediaType.APPLICATION_JSON);
}else {
ErrorEntity entity = new ErrorEntity(ErrorCode.OTHER_ERR.getCode(),e.getMessage());
ResponseBuilder = Response.ok(entity, MediaType.APPLICATION_JSON);
}
System.out.println("執行自定義異常");
return ResponseBuilder.build();
}
}
public class RESTApplication extends ResourceConfig {
public RESTApplication() {
//想讓jersey托管的部分需要加入掃描,或者使用register指定托管類也可以
packages("com.haikong.resources","com.haikong.exception");
//加載日志包
register(LoggingFilter.class);
//加載json轉換器
register(JacksonJsonProvider.class);
System.out.println("加載RESTApplication");
}
}
/** * 測試全局異常托管 * @throws DeviceException */ @GET @Path("/testexception") public void testException() throws DeviceException { if (true){ throw new DeviceException(ErrorCode.OTHER_ERR); } }
{
"resp_code": 2,
"resp_msg": "未知錯誤"
}
資源實例下載:http://download.csdn.net/detail/sotong006/9913077
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。