Spring Boot HTTP over JSON 的错误码异常处理

This commit is contained in:
JeffLi1993
2017-03-14 14:56:45 +08:00
committed by liqiangqiang
parent 0dad83ad48
commit ecfcb02e8d
3 changed files with 53 additions and 9 deletions

View File

@@ -0,0 +1,28 @@
package org.spring.springboot.result;
/**
* 应用系统级别的错误码
*
* Created by bysocket on 14/03/2017.
*/
public enum GlobalErrorInfoEnum implements ErrorInfoInterface{
SUCCESS("0", "success"),
NOT_FOUND("-1", "service not found");
private String code;
private String message;
GlobalErrorInfoEnum(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode(){
return this.code;
}
public String getMessage(){
return this.message;
}
}

View File

@@ -5,7 +5,7 @@ package org.spring.springboot.result;
*
* Created by bysocket on 14/03/2017.
*/
public class ResultBody<T> {
public class ResultBody {
/**
* 响应代码
*/
@@ -19,13 +19,19 @@ public class ResultBody<T> {
/**
* 响应结果
*/
private T result;
private Object result;
public ResultBody(ErrorInfoInterface errorInfo) {
this.code = errorInfo.getCode();
this.message = errorInfo.getMessage();
}
public ResultBody(Object result) {
this.code = GlobalErrorInfoEnum.SUCCESS.getCode();
this.message = GlobalErrorInfoEnum.SUCCESS.getMessage();
this.result = result;
}
public String getCode() {
return code;
}
@@ -42,11 +48,11 @@ public class ResultBody<T> {
this.message = message;
}
public T getResult() {
public Object getResult() {
return result;
}
public void setResult(T result) {
public void setResult(Object result) {
this.result = result;
}
}

View File

@@ -2,7 +2,11 @@ package org.spring.springboot.web;
import org.spring.springboot.constant.CityErrorInfoEnum;
import org.spring.springboot.result.GlobalErrorInfoException;
import org.spring.springboot.result.ResultBody;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
@@ -13,14 +17,20 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class ErrorJsonController {
/**
* 模拟入参不完整案例
* 获取城市接口
*
* @param cityName
* @return
* @throws GlobalErrorInfoException
*/
@RequestMapping("/param")
public String errorJsonParams() throws GlobalErrorInfoException {
throw new GlobalErrorInfoException(CityErrorInfoEnum.PARAMS_NO_COMPLETE);
@RequestMapping(value = "/api/city", method = RequestMethod.GET)
public ResultBody findOneCity(@RequestParam("cityName") String cityName) throws GlobalErrorInfoException {
// 入参为空
if (StringUtils.isEmpty(cityName)) {
throw new GlobalErrorInfoException(CityErrorInfoEnum.PARAMS_NO_COMPLETE);
}
return new ResultBody(new City(1L,2L,"温岭","是我的故乡"));
}
}
}