IT/slack

slack으로 오류사항 받기 2 (slack api)

토희 2023. 8. 14. 10:03
728x90

slack으로 오류사항 받기 1 (slack api) 에서 테스트 연동을 하고 이제 프로젝트에 적용해본다

 

controllerAdvice

@RestControllerAdvice
@RequiredArgsConstructor
public class ControllerAdvisor {

    private final SlackService slackService;

    @ExceptionHandler(Exception.class)
    public void SlackErrorMessage(Exception e){
        slackService.sendErrorForSlack(e);
    }
    
    @ExceptionHandler(PasswordEmailSendException.class)
    public ResponseEntity<ExceptionResponse> passwordEmailSendException(PasswordEmailSendException e) {
        int statusCode = e.getStatusCode();

        ExceptionResponse response = ExceptionResponse.builder()
                .code(String.valueOf(statusCode))
                .message(e.getMessage())
                .validation(e.getValidation())
                .build();

        return ResponseEntity.status(statusCode).body(response);
    }

 }

 

controller

@RestController
@RequiredArgsConstructor
public class SlackController {
    
    @GetMapping(value = "/error/v1")
    public String ErrorSlackClient1() {
        throw new ReadOnlyBufferException();
    }

    @GetMapping(value = "/error/v2")
    public String ErrorSlackClient2() {
        throw new PasswordEmailSendException();
    }

}

 

테스트를 위해 controller에서 핸들링 해준 에러(PasswordEmailSendException) 와 그렇지 않은 에러(ReadOnlyBufferException) 두 개를 작성해준다

 

Service

@Slf4j
@Service
@RequiredArgsConstructor
public class SlackService {

    @Value("${notification.slack.webhook.url}")
    private String slackWebhookUrl;

    private final HttpServletRequest request;

    public String sendErrorForSlack(Exception exception) {
        Slack slack = Slack.getInstance();
        WebhookResponse response;
        try {
            StringWriter writer = new StringWriter();
            exception.printStackTrace(new PrintWriter(writer));

            String emoji = "\u2620";
            String errorTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String errorPath = request.getRequestURI().toString();
            String exceptionName = exception.getClass().toString();
            String exceptionRoot = exception.getStackTrace()[0].toString();
            String message = String.format("%s [%s] - [%s] - [%s] - [%s]", emoji, errorTime, errorPath, exceptionName, exceptionRoot);

            Payload payload = Payload.builder().text(message).build();
            response = slack.send(slackWebhookUrl, payload);
            return "Slack Sent = " + response.getCode();

        } catch (IOException e) {
        	// TODO 예외처리
            log.error("Error sending for slack", e);
        }
        return null;
    }

}

String message 부분에서는 커스텀 해서 마음대로 보내면 된다

나는 추척하가 쉽게 어느 부분에서 어떻난 에러가 났는지 메세지를 보낸다

 

 

스웨거 테스트

핸들링한 에러 발생시, 슬랙에는 아무것도 뜨지 않는다

 

핸들링 하지 않은 에러 발생시

 

슬랙에 위와 같은 알림 메세지가 뜬다!!

 

 

 

++ 

controllerAdvice를 위와 같이 작성하니 

controller 단에서 httpStatus에서 설정을 하면 그 코드가 내려가는게 아니구 200코드로 내려가서

@ExceptionHandler(Exception.class)
public ResponseEntity<ExceptionResponse> SlackErrorMessage(Exception e){
    slackApi.sendErrorForSlack(e);

    ExceptionResponse response = ExceptionResponse.builder()
            .code(String.valueOf(500))
            .message(e.getMessage())
            .build();

    return ResponseEntity.status(500).body(response);
}

이렇게 바꿔줌

728x90

'IT > slack' 카테고리의 다른 글

slack으로 오류사항 받기 1 (slack api)  (0) 2023.08.10