Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEAT] slack 알림 구현 #206

Merged
merged 3 commits into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .gitmessage.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

################
# [FEAT] : 기능 추가 및 구현
# [FIX] : 에러 발생 시, 버그
# [REFACTOR] : 기존 코드에서 기능 추가 및 개선
# [HOTFIX] : 급한 수정 , 배포 후 수정
# [TEST] : Test code
# [RENAME] : 변수명, 메소드명, 클래스명 변경
# [CHORE] : 사소한 코드 수정, 디렉토리 구조 변경, 변수명 변경, 불필요한 코드 삭제(import)
# [DOCS] : 주석 및 Readme
# [CONFIG] : 의존성 추가, 설정 파일 추가
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ dependencies {
annotationProcessor "jakarta.annotation:jakarta.annotation-api"
annotationProcessor "jakarta.persistence:jakarta.persistence-api"

// slack
implementation("com.slack.api:slack-api-client:1.31.0")

// AWS sdk
implementation("software.amazon.awssdk:bom:2.21.0")
implementation("software.amazon.awssdk:s3:2.21.0")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package site.katchup.katchupserver.common.advice;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
Expand All @@ -8,19 +9,41 @@
import org.springframework.web.bind.annotation.RestControllerAdvice;
import site.katchup.katchupserver.common.dto.ApiResponseDto;
import site.katchup.katchupserver.common.exception.BaseException;
import site.katchup.katchupserver.common.exception.InternalServerException;
import site.katchup.katchupserver.common.response.ErrorCode;
import site.katchup.katchupserver.external.slack.SlackService;

import static site.katchup.katchupserver.common.response.ErrorCode.VALIDATION_REQUEST_MISSING_EXCEPTION;


@RestControllerAdvice
public class ControllerExceptionAdvice {

private final String channel;

public ControllerExceptionAdvice(@Value("${slack.channel}") final String channel, SlackService slackService) {
this.channel = channel;
this.slackService = slackService;
}

private final SlackService slackService;

@ExceptionHandler(BaseException.class)
public ResponseEntity<ApiResponseDto> handleGlobalException(BaseException ex) {
if (ex.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) {
slackService.sendMessage(channel, ex.getMessage());
}
return ResponseEntity.status(ex.getStatusCode())
.body(ApiResponseDto.error(ex.getCode()));
}

@ExceptionHandler(InternalServerException.class)
public ResponseEntity<ApiResponseDto> handleInternalServerException(InternalServerException ex) {
slackService.sendMessage(channel, ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ApiResponseDto.error(ErrorCode.INTERNAL_SERVER_ERROR.getCode()));
}

@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<ApiResponseDto> handleMissingParameter(MissingServletRequestParameterException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package site.katchup.katchupserver.external.slack;


import com.slack.api.Slack;
import com.slack.api.methods.SlackApiException;
import com.slack.api.methods.response.chat.ChatPostMessageResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;

@Service
@RequiredArgsConstructor
public class SlackService {

@Value("${slack.bot-token}")
private String SLACK_TOKEN;

private final Environment env;

public void sendMessage(String channel, String text) {
try {
Slack slack = Slack.getInstance();
ChatPostMessageResponse response = slack.methods(SLACK_TOKEN).chatPostMessage(req -> req
.channel(channel)
.text("[" + getProfiles() + "]" + text));
System.out.println(response);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

p5;

확인을 위한 출력문이었을까요 ??

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아 그러네요 지우겠습니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@RestControllerAdvice가 있는 Exception Handling을 하는 클래스에서 따로 처리해도 좋을 것 같고, 만약 slack에 띄울 게 아니라면 logging이나 모니터링 tool 을 도입해도 좋을 것 같습니다!

} catch (IOException | SlackApiException e) {
throw new RuntimeException(e);
}
}

private String getProfiles() {
return Arrays.stream(env.getActiveProfiles()).findFirst().orElse("");
}
}
3 changes: 3 additions & 0 deletions src/main/resources/application-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,6 @@ springdoc:
path: /api-docs/json
groups:
enabled: true
slack:
bot-token: ${SLACK_BOT_TOKEN}
channel: ${SLACK_ALERT_CHANNEL}
6 changes: 5 additions & 1 deletion src/main/resources/application-local.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,8 @@ aws-property:
aws-region: ${AWS_REGION}
s3-bucket-name: ${AWS_BUCKET_NAME}
access-key: ${AWS_ACCESS_KEY}
secret-key: ${AWS_SECRET_KEY}
secret-key: ${AWS_SECRET_KEY}

slack:
bot-token: ${SLACK_BOT_TOKEN}
channel: ${SLACK_ALERT_CHANNEL}
Loading