Skip to content

Commit

Permalink
perf($ApiGateway): handle service not available exception
Browse files Browse the repository at this point in the history
  • Loading branch information
Johnny Miller (锺俊) committed Dec 23, 2020
1 parent 0d3f265 commit 235bcb8
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jmsoftware.maf.common.bean.ResponseBodyBean;
import com.jmsoftware.maf.muscleandfitnessserverreactivespringbootstarter.util.RequestUtil;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
Expand Down Expand Up @@ -37,10 +38,9 @@ public class GlobalExceptionHandler implements ErrorWebExceptionHandler {
@SuppressWarnings("NullableProblems")
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
val request = exchange.getRequest();
log.error("Exception occurred when [{}] requested access. Request URL: [{}] {}",
RequestUtil.getRequestIpAndPort(request), request.getMethod(), request.getURI());
log.error("Exception occurred when [{}] requested access. Exception message: {}. Request URL: [{}] {}",
RequestUtil.getRequestIpAndPort(request), ex.getMessage(), request.getMethod(), request.getURI(), ex);
ServerHttpResponse response = exchange.getResponse();
log.error(ex.getMessage(), ex.fillInStackTrace());
if (response.isCommitted()) {
return Mono.error(ex);
}
Expand Down Expand Up @@ -69,6 +69,9 @@ private ResponseBodyBean<?> setResponseBody(ServerHttpResponse response, Throwab
if (ex instanceof ResponseStatusException) {
response.setStatusCode(((ResponseStatusException) ex).getStatus());
return ResponseBodyBean.ofStatus(((ResponseStatusException) ex).getStatus());
} else if (ex instanceof HystrixRuntimeException) {
response.setStatusCode(HttpStatus.SERVICE_UNAVAILABLE);
return ResponseBodyBean.ofStatus(HttpStatus.SERVICE_UNAVAILABLE, ex.getMessage());
}
response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
return ResponseBodyBean.ofStatus(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,23 @@ public static <ResponseBodyDataType> ResponseBodyBean<ResponseBodyDataType> ofSt
.build();
}

/**
* Of status response body bean.
*
* @param <ResponseBodyDataType> the type parameter
* @param status the status
* @param message the message
* @return the response body bean
*/
public static <ResponseBodyDataType> ResponseBodyBean<ResponseBodyDataType> ofStatus(@NonNull final HttpStatus status,
@NonNull final String message) {
return ResponseBodyBean.<ResponseBodyDataType>builder()
.timestamp(new Date())
.status(status.value())
.message(message)
.build();
}

/**
* <p>Respond to client with IUniversalStatus and data.</p>
* <p><strong>ATTENTION:</strong></p>
Expand All @@ -82,7 +99,7 @@ public static <ResponseBodyDataType> ResponseBodyBean<ResponseBodyDataType> ofSt
* @return response body for ExceptionControllerAdvice
*/
public static <ResponseBodyDataType> ResponseBodyBean<ResponseBodyDataType> ofStatus(@NonNull final HttpStatus status,
@NonNull final ResponseBodyDataType data) {
final ResponseBodyDataType data) {
return ResponseBodyBean.<ResponseBodyDataType>builder()
.timestamp(new Date())
.status(status.value())
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
package com.jmsoftware.maf.muscleandfitnessserverreactivespringbootstarter.util;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jmsoftware.maf.common.bean.ResponseBodyBean;
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.val;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
* Description: ResponseUtil, change description here.
*
Expand All @@ -31,13 +29,19 @@ public class ResponseUtil {
@SneakyThrows
public static Mono<Void> renderJson(@NonNull ServerWebExchange exchange, @NonNull HttpStatus httpStatus,
@Nullable Object data) {
ObjectMapper objectMapper = new ObjectMapper();
exchange.getResponse().setStatusCode(httpStatus);
val response = exchange.getResponse();
JSON json = ResponseBodyBean.of(httpStatus.getReasonPhrase(), data, httpStatus.value());
val responseBodyBytes = JSONUtil.toJsonStr(json).getBytes(StandardCharsets.UTF_8);
DataBuffer dataBuffer = response.bufferFactory().wrap(responseBodyBytes);
response.setStatusCode(httpStatus);
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
return response.writeWith(Mono.just(dataBuffer));
response.getHeaders().set("Content-Type", "application/json;charset=UTF-8");
return response.writeWith(Mono.fromSupplier(() -> {
DataBufferFactory bufferFactory = response.bufferFactory();
final var responseBody = ResponseBodyBean.ofStatus(httpStatus, data);
try {
return bufferFactory.wrap(objectMapper.writeValueAsBytes(responseBody));
} catch (JsonProcessingException e) {
return bufferFactory.wrap(new byte[0]);
}
}));
}
}

0 comments on commit 235bcb8

Please sign in to comment.