Skip to content

Commit

Permalink
perf($APIGateway): simplify global exception error
Browse files Browse the repository at this point in the history
  • Loading branch information
johnnymillergh committed Jan 19, 2021
1 parent bd81092 commit ff82751
Showing 1 changed file with 28 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.jmsoftware.maf.apigateway.universal.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jmsoftware.maf.common.bean.ResponseBodyBean;
Expand All @@ -22,6 +23,8 @@
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Optional;

/**
* <h1>GlobalExceptionHandler</h1>
* <p>
Expand Down Expand Up @@ -79,8 +82,31 @@ private ResponseBodyBean<?> setResponseBody(ServerHttpResponse response, Throwab
val cause = (FeignException) ex.getCause();
val httpStatus = HttpStatus.valueOf(cause.status());
response.setStatusCode(httpStatus);
return ResponseBodyBean.ofStatus(httpStatus,
String.format("%s %s", ex.getMessage(), ex.getCause().getMessage()));
String responseBodyString = null;
if (cause.responseBody().isPresent()) {
responseBodyString = new String(cause.responseBody().get().array());
}
Optional<ResponseBodyBean<?>> optionalResponseBodyBean = Optional.empty();
if (StrUtil.isNotBlank(responseBodyString)) {
try {
//noinspection unchecked
optionalResponseBodyBean = Optional.ofNullable(
objectMapper.readValue(responseBodyString, ResponseBodyBean.class));
} catch (JsonProcessingException e) {
log.error("Cannot deserialize response to {}", ResponseBodyBean.class.getSimpleName());
optionalResponseBodyBean = Optional.empty();
}
}
String errorMessage;
if (optionalResponseBodyBean.isPresent() && StrUtil.isNotBlank(
optionalResponseBodyBean.get().getMessage())) {
errorMessage = String.format("%s Feign exception: %s", ex.getMessage(),
optionalResponseBodyBean.get().getMessage());
} else {
errorMessage = String.format("%s Feign exception: %s", ex.getMessage(),
ex.getCause().getMessage());
}
return ResponseBodyBean.ofStatus(httpStatus, errorMessage);
}
response.setStatusCode(HttpStatus.SERVICE_UNAVAILABLE);
return ResponseBodyBean.ofStatus(HttpStatus.SERVICE_UNAVAILABLE,
Expand Down

0 comments on commit ff82751

Please sign in to comment.