Skip to content

Commit

Permalink
perf($Authentication): capture request filter exception
Browse files Browse the repository at this point in the history
  • Loading branch information
johnnymillergh committed May 13, 2020
1 parent a9e69e8 commit 85d105c
Showing 1 changed file with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.jmsoftware.common.exception.SecurityException;
import com.jmsoftware.common.util.RequestUtil;
import com.jmsoftware.common.util.ResponseUtil;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
Expand Down Expand Up @@ -95,7 +96,19 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
log.info("JWT authentication passed! Authentication: {}", authentication);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
try {
filterChain.doFilter(request, response);
} catch (Exception e) {
log.error("Exception occurred when filtering request. Exception message: {}", e.getMessage(), e);
val exception = recursiveTraverseExceptionCause(e);
if (exception instanceof SecurityException) {
val code = ((SecurityException) exception).getCode();
final var httpStatus = HttpStatus.fromCode(code);
ResponseUtil.renderJson(response, httpStatus, exception.getMessage());
return;
}
ResponseUtil.renderJson(response, HttpStatus.ERROR, e.getMessage());
}
}

/**
Expand Down Expand Up @@ -155,4 +168,19 @@ private boolean checkIgnores(HttpServletRequest request) {
}
return false;
}

/**
* Recursive traverse exception cause exception.
*
* @param exception the exception
* @return the exception
* @author Johnny Miller (鍾俊), e-mail: johnnysviva@outlook.com
* @date 5/13/20 4:51 PM
*/
private Exception recursiveTraverseExceptionCause(@NonNull Exception exception) {
if (ObjectUtil.isNotNull(exception.getCause())) {
return recursiveTraverseExceptionCause((Exception) exception.getCause());
}
return exception;
}
}

0 comments on commit 85d105c

Please sign in to comment.