Skip to content

Commit

Permalink
refactor: fix GlobalExceptionHandler to send slack error for INTERNAL…
Browse files Browse the repository at this point in the history
…_SERVER_ERROR only
  • Loading branch information
gmkim20713 committed Aug 15, 2024
1 parent 410a193 commit 5028aee
Showing 1 changed file with 22 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

Expand All @@ -19,8 +20,17 @@ public class GlobalExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
private final SlackService slackService;

@ExceptionHandler(ResponseStatusException.class)
public Mono<ResponseEntity<String>> handleResponseStatusException(ServerWebExchange exchange, ResponseStatusException ex) {
return handleExceptionInternal(exchange, ex, (HttpStatus) ex.getStatusCode());
}

@ExceptionHandler(Exception.class)
public Mono<ResponseEntity<String>> handleException(ServerWebExchange exchange, Exception ex) {
public Mono<ResponseEntity<String>> handleGenericException(ServerWebExchange exchange, Exception ex) {
return handleExceptionInternal(exchange, ex, HttpStatus.INTERNAL_SERVER_ERROR);
}

private Mono<ResponseEntity<String>> handleExceptionInternal(ServerWebExchange exchange, Exception ex, HttpStatus status) {
String method = exchange.getRequest().getMethod().toString();
String userAgent = exchange.getRequest().getHeaders().getFirst("User-Agent");
String proxyIp = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For");
Expand All @@ -31,14 +41,16 @@ public Mono<ResponseEntity<String>> handleException(ServerWebExchange exchange,

logger.error("Exception occurred: {} {} {} ERROR {} {}", method, fullPath, originIp, ex.getMessage(), userAgent);

return slackService.sendErrorNotification(
method,
fullPath,
originIp,
userAgent,
ex.getMessage()
).then(
Mono.just(new ResponseEntity<>("Internal Server Error", HttpStatus.INTERNAL_SERVER_ERROR))
);
if (status == HttpStatus.INTERNAL_SERVER_ERROR) {
return slackService.sendErrorNotification(
method,
fullPath,
originIp,
userAgent,
ex.getMessage()
).then(Mono.just(new ResponseEntity<>("Internal Server Error", HttpStatus.INTERNAL_SERVER_ERROR)));
}

return Mono.just(new ResponseEntity<>(status.getReasonPhrase(), status));
}
}

0 comments on commit 5028aee

Please sign in to comment.