Exception异常处理改造
接口调用返回异常结果如下
Response Body返回参数:
新建传入Id后返回业务Code:
12345678910 {
"entityName": "virtualRules",
"errorKey": "business",
"statusCode": 7002,
"type": "http://www.jhipster.tech/problem/problem-with-message",
"title": "新增接口,ID必须为空",
"status": 400,
"message": "error.business",
"params": "virtualRules"
}
Response Headers返回参数:
1234567891011121314 {
"pragma": "no-cache",
"date": "Wed, 25 Apr 2018 08:50:07 GMT",
"x-content-type-options": "nosniff",
"transfer-encoding": "chunked",
"content-type": "application/problem+json",
"cache-control": "no-cache, no-store, max-age=0, must-revalidate",
"status_code": "7002",
"connection": "keep-alive",
"status_msg": "dmlydHVhbFJ1bGVzLGJ1c2luZXNzLOaWsOWinuaOpeWPo++8jElE5b+F6aG75Li656m6",
"x-xss-protection": "1; mode=block",
"x-application-context": "boss-gateway:swagger,local:8080",
"expires": "0"
}
具体修改如下:
找到ExceptionTranslator.java
1. 修改feignClientException方法(feign调用异常处理类)
1234567891011121314151617181920212223242526272829303132333435 HystrixRuntimeException.class)
public ResponseEntity feignClentException(HystrixRuntimeException ex){
if(ex.getCause() instanceof FeignException){
log.debug("异常信息 {}",ex);
FeignException e = (FeignException) ex.getCause();</font>
HttpHeaders httpHeaders = new HttpHeaders();
if(e.status()==400){
String msg = e.getMessage();
String msgJson = msg.substring(msg.indexOf("{"));
JSONObject jsonObject = JSONObject.parseObject(msgJson);
String title = jsonObject.getString("title");
String statusCode = jsonObject.getString("statusCode");
httpHeaders.add("status_code", statusCode);
httpHeaders.add("status_msg", getBase64Code(title));
}else {
httpHeaders.add("status_code", e.status() + "");
httpHeaders.add("status_msg", getBase64Code(e.getMessage()));
}
return new ResponseEntity(null,httpHeaders,HttpStatus.valueOf(e.status()));
}
return this.globalExceptionHandler(ex);
}
新增代码
if(e.status()==400){
String msg = e.getMessage();
String msgJson = msg.substring(msg.indexOf("{"));
JSONObject jsonObject = JSONObject.parseObject(msgJson);
String title = jsonObject.getString("title");
String statusCode = jsonObject.getString("statusCode");
httpHeaders.add("status_code", statusCode);
httpHeaders.add("status_msg", getBase64Code(title));
}else {}
(
该方法为了解决feign之间相互调用异常处理。异常代码如下:
1234567891011 status 400 reading ConnectVariableManager#insertConnectVariable(String,ConnectVariableDTO); content:
{
"entityName" : "bControllerVariables",
"errorKey" : "VariableNameexists",
"type" : "http://www.jhipster.tech/problem/problem-with-message",
"title" : "连接变量名称已存在!",
"statusCode": 7002,
"status" : 400,
"message" : "error.VariableNameexists",
"params" : "bControllerVariables"
}
2.业务异常修改方式
12345678 RequestAlertException.class)
public ResponseEntity<!--?--> handleBadRequestAlertException(RequestAlertException ex, NativeWebRequest request) {
log.debug("异常信息 {}",ex);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("status_code",ex.getStatusCode()+"");
httpHeaders.add("status_msg",getBase64Code(ex.getEntityName()+","+ex.getErrorKey()+","+ex.getMessage()));
return create(ex, request, httpHeaders);
}
(
二、添加RequestAlertException类
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 public class RequestAlertException extends AbstractThrowableProblem {
private final String entityName;
private final String errorKey;
private Integer statusCode;
public RequestAlertException(String defaultMessage, String entityName, String errorKey) {
this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, errorKey);
}
public RequestAlertException(JsonResultStatus status,String entityName) {
this(ErrorConstants.DEFAULT_TYPE, status.getReasonPhrase(), entityName, "business");
this.statusCode = status.getStatusCode();
}
public RequestAlertException(JsonResultStatus status,String defaultMessage,String entityName) {
this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, status.getReasonPhrase());
this.statusCode = status.getStatusCode();
}
public RequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) {
super(type, defaultMessage, Status.BAD_REQUEST, null, null, null, getAlertParameters(entityName, errorKey));
this.entityName = entityName;
this.errorKey = errorKey;
}
public String getEntityName() {
return entityName;
}
public String getErrorKey() {
return errorKey;
}
public Integer getStatusCode() {
return statusCode;
}
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}
private static Map<string, object=""> getAlertParameters(String entityName, String errorKey) {
Map<string, object=""> parameters = new HashMap<>();
parameters.put("message", "error." + errorKey);
parameters.put("params", entityName);
return parameters;
}
statusCode 代表业务异常代码需要从 JsonResultStatus中获取Status.BAD_REQUEST来改变HTTP异常代码
123456 public RequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) {
super(type, defaultMessage, Status.BAD_REQUEST, null, null, null, getAlertParameters(entityName, errorKey));
this.entityName = entityName;
this.errorKey = errorKey;
}
JsonResultStatus code和message对应关系:
1234 public RequestAlertException(JsonResultStatus status,String entityName) {
this(ErrorConstants.DEFAULT_TYPE, status.getReasonPhrase(), entityName, "business");
this.statusCode = status.getStatusCode();
}
status.getStatusCode() == code 枚举类code
status.getReasonPhrase() == message 枚举类message
三、添加JsonResultStatus类
import org.zalando.problem.StatusType;
/***
* JSON数据返回状态码
* ClassName: JsonResultStatus
*
* @Description: JSON数据返回状态码
* @author
* @date
*/
public enum JsonResultStatus implements StatusType {
SUCCESS(200,"执行成功"),
REQ_REDIRECT(301,"请求已被永久移动到新位置"),
REQ_GRAMMAR_ERROR(400,"服务器不理解请求的语法"),
REQ_UN_AUTHORIZED(401,"API访问资源未授权"),
REQ_REFUSE(403,"访问被服务器拒绝"),
REQ_NOT_FOUND(404,"请求地址不存在"),
REQ_EMPTY_PARAMS(406,"请求参数错误或为空"),
REQ_NOT_OVERTIME(408,"服务器等候请求时超时"),
SYS_EXCEPTION(500,"系统服务存在异常"),
SYS_UNENFORCED(501,"服务器不具备完成请求的功能"),
SYS_GATEWAY_ERROR(502,"服务器作为网关或代理,从后续服务收到了无效的响应"),
SYS_UNAVAILABLE_ERROR(503,"目前无法使用服务(由于超载或进行停机维护)"),
SYS_GATEWAY_TIMEOUT(504,"服务器作为网关或代理,未及时从后续服务接收请求"),
SYS_VERSION_ERROR(505,"HTTP版本不被支持"),
NO_LOGIN(600,"用户未登录或登录已失效"),
NO_RECORDS(691,"记录不存在"),
NO_CROSS(692,"不允许跨域访问"),
HTTP_REQ_ERROR(900,"服务请求失败"),
USER_TENANT_MATCHING_ERROR(902,"用户请求与所属租户不匹配"),
HTTP_URL_ERROR(903,"请求地址非法或为空"),
USER_TENANT_LOST_ERROR(904,"用户所属租户序号丢失"),
VISITOR_URL_RESOURCES_LOST(905,"访客权限资源丢失,请求被拒绝"),
USER_TENANT_CHANGE_ERROR(906,"请求失败,登陆用户信息已被篡改"),
DATA_NOT_ALLOW(7001,"当前设备的规则已经超过5个,不支持添加。"),
ID_EXIST(7002,"新增接口,ID必须为空"),
IDS_NOT_NULL(7003,"ID 不能为空"),
DATA(7499,"DATA");
private final int code;
private final String reason;
JsonResultStatus(final int statusCode, final String reasonPhrase) {
this.code = statusCode;
this.reason = reasonPhrase;
}
public int getStatusCode() {
return code;
}
public String getReasonPhrase() {
return reason;
}
}
自定义枚举
ID_EXIST(7002,"新增接口,ID必须为空"),
VirtualRulesResource类示例:
123456789101112131415161718192021222324 /**
* POST 新建规则
* @param virtualRulesDTO
* @return
*/
("/virtual-rules")
(value = "新建入库",httpMethod = "POST",response = VirtualRulesDTO.class ,notes = "新建入库")
public ResponseEntity<!--?--> saveVirtualRulesDTO( VirtualRulesDTO virtualRulesDTO) throws URISyntaxException {
log.debug("新建入库 : {}", virtualRulesDTO);
log.debug("REST request to save virtualRules : {}", virtualRulesDTO);
if (virtualRulesDTO.getId() != null) {
throw new RequestAlertException(JsonResultStatus.ID_EXIST, ENTITY_NAME);
}
virtualRulesDTO.setThingVersion((Integer.parseInt(virtualRulesDTO.getThingVersion())+1)+"");
virtualRulesDTO.setDelFlag("0");
VirtualRulesDTO result = virtualRulesService.saveVirtualRules(virtualRulesDTO);
return ResponseEntity.created(new URI("/api/v1/virtual-rules/" + result.getId().toString()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
if (virtualRulesDTO.getId() != null) {
throw new RequestAlertException(JsonResultStatus.ID_EXIST, ENTITY_NAME);
}
测试接口如下
Response Body返回参数:
新建传入Id后返回业务Code:
“statusCode”: 7002,HttpCode:“status”: 400
12345678910 {
"entityName": "virtualRules",
"errorKey": "business",
"statusCode": 7002,
"type": "http://www.jhipster.tech/problem/problem-with-message",
"title": "新增接口,ID必须为空",
"status": 400,
"message": "error.business",
"params": "virtualRules"
}
Response Headers返回参数:
1234567891011121314 {
"pragma": "no-cache",
"date": "Wed, 25 Apr 2018 08:50:07 GMT",
"x-content-type-options": "nosniff",
"transfer-encoding": "chunked",
"content-type": "application/problem+json",
"cache-control": "no-cache, no-store, max-age=0, must-revalidate",
"status_code": "7002",
"connection": "keep-alive",
"status_msg": "dmlydHVhbFJ1bGVzLGJ1c2luZXNzLOaWsOWinuaOpeWPo++8jElE5b+F6aG75Li656m6",
"x-xss-protection": "1; mode=block",
"x-application-context": "boss-gateway:swagger,local:8080",
"expires": "0"
}