Skip to content

Commit

Permalink
perf($api-gateway): refine exception handling
Browse files Browse the repository at this point in the history
  • Loading branch information
johnnymillergh committed Jun 20, 2021
1 parent 3dc2dc0 commit b5e1340
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,9 @@ private ResponseBodyBean<?> setResponseBody(ServerHttpResponse response, Throwab
try {
return objectMapper.readValue(exception.getResponseBodyAsString(), ResponseBodyBean.class);
} catch (JsonProcessingException e) {
log.warn("Exception occurred when writing response", e);
return ResponseBodyBean.ofStatus(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
log.warn("Exception occurred when writing response. Exception message: {}", e.getMessage());
return ResponseBodyBean.ofStatus(exception.getStatusCode(),
exception.getResponseBodyAsString(StandardCharsets.UTF_8));
}
}
response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.jmsoftware.maf.springcloudstarter.aspect;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.jmsoftware.maf.common.bean.ResponseBodyBean;
Expand All @@ -26,6 +27,7 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.Objects;

/**
Expand Down Expand Up @@ -200,6 +202,20 @@ public ResponseBodyBean<?> handlePersistenceException(HttpServletRequest request
removeLineSeparator(exception.getMessage())));
}

@ExceptionHandler(UndeclaredThrowableException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseBodyBean<?> handleError(UndeclaredThrowableException exception) {
log.error("Undeclared throwable exception occurred! Exception message: {} ", exception.getMessage(), exception);
if (ObjectUtil.isNotNull(exception.getCause()) && StrUtil.isNotEmpty(exception.getCause().getMessage())) {
return ResponseBodyBean.ofStatus(HttpStatus.INTERNAL_SERVER_ERROR,
String.format("Exception message: %s",
removeLineSeparator(exception.getCause().getMessage())));
}
return ResponseBodyBean.ofStatus(HttpStatus.INTERNAL_SERVER_ERROR,
String.format("Exception message: %s",
removeLineSeparator(exception.getMessage())));
}

@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseBodyBean<?> handleError(Throwable ex) {
Expand Down

0 comments on commit b5e1340

Please sign in to comment.