Skip to content

Commit

Permalink
[YS-155] refact: 예외 핸들링 로직 수정 및 500 에러 디스코드 웹훅 알림 추가 (#37)
Browse files Browse the repository at this point in the history
* feat: implement Discord error alarm notification feature

* refact: delete unused file

* chore: add discord env

* chore: add discord env in test yml

* refact: rename request dto name

* style: delete unused import
  • Loading branch information
Ji-soo708 authored Jan 17, 2025
1 parent 5158eae commit bdb301c
Show file tree
Hide file tree
Showing 10 changed files with 129 additions and 23 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package com.dobby.backend.domain.exception

import org.springframework.http.HttpStatus

open class DomainException(
val errorCode: ErrorCode,
val data: Any? = null,
) : RuntimeException(errorCode.message)

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.dobby.backend.domain.gateway

import jakarta.servlet.http.HttpServletRequest

interface AlertGateway {
fun sendError(e: Exception, request: HttpServletRequest)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.dobby.backend.infrastructure.feign.discord

import com.dobby.backend.presentation.api.dto.request.DiscordMessageRequest
import org.springframework.cloud.openfeign.FeignClient
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody

@FeignClient(
name = "discord-alarm-feign-client",
url = "\${discord.webhook-url}"
)
interface DiscordFeignClient {

@PostMapping(produces = [MediaType.APPLICATION_JSON_VALUE])
fun sendMessage(@RequestBody discordMessageRequest: DiscordMessageRequest)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.dobby.backend.infrastructure.gateway.discord

import com.dobby.backend.domain.gateway.AlertGateway
import com.dobby.backend.infrastructure.feign.discord.DiscordFeignClient
import com.dobby.backend.presentation.api.dto.request.DiscordMessageRequest
import jakarta.servlet.http.HttpServletRequest
import org.springframework.stereotype.Component
import java.io.PrintWriter
import java.io.StringWriter
import java.time.LocalDateTime

@Component
class AlertGatewayImpl(
private val discordFeignClient: DiscordFeignClient
): AlertGateway {

override fun sendError(e: Exception, request: HttpServletRequest) {
sendMessage(createMessage(e, request))
}

private fun createMessage(e: Exception, request: HttpServletRequest): DiscordMessageRequest {
return DiscordMessageRequest(
content = "# 🚨 에러 발생 비이이이이사아아아앙",
embeds = listOf(
DiscordMessageRequest.Embed(
title = "ℹ️ 에러 정보",
description = """
### 🕖 발생 시간
${LocalDateTime.now()}
### 🔗 요청 URL
${createRequestFullPath(request)}
### 📄 Stack Trace
```
${getStackTrace(e).substring(0, 1000)}
```
""".trimIndent()
)
)
)
}

private fun createRequestFullPath(request: HttpServletRequest): String {
var fullPath = "${request.method} ${request.requestURL}"

val queryString = request.queryString
if (queryString != null) {
fullPath += "?$queryString"
}

return fullPath
}

private fun getStackTrace(e: Exception): String {
val stringWriter = StringWriter()
e.printStackTrace(PrintWriter(stringWriter))
return stringWriter.toString()
}

private fun sendMessage(request: DiscordMessageRequest) {
discordFeignClient.sendMessage(request)
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package com.dobby.backend.presentation.api.config

import com.dobby.backend.domain.exception.*
import com.dobby.backend.domain.gateway.AlertGateway
import com.dobby.backend.presentation.api.dto.response.ErrorResponse
import jakarta.servlet.http.HttpServletRequest
import jakarta.validation.ConstraintViolationException
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.http.converter.HttpMessageNotReadableException
Expand All @@ -18,7 +21,10 @@ import org.springframework.web.util.BindErrorUtils
import java.security.InvalidParameterException

@RestControllerAdvice
class WebExceptionHandler {
class WebExceptionHandler(
private val alertGateway: AlertGateway
) {
private val logger: Logger = LoggerFactory.getLogger(WebExceptionHandler::class.java)

@ExceptionHandler(value = [DomainException::class])
fun handleDomainException(
Expand Down Expand Up @@ -94,6 +100,18 @@ class WebExceptionHandler {
)
}

@ExceptionHandler(value = [Throwable::class])
fun handleUnhandledException(
exception: Exception,
request: HttpServletRequest
): ResponseEntity<ErrorResponse> {
alertGateway.sendError(exception, request)
logger.error("[UnhandledException] " + exception.stackTraceToString())
return ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ErrorResponse.fromErrorCode(ErrorCode.UNKNOWN_SERVER_ERROR))
}

@ExceptionHandler(value = [AuthenticationException::class])
fun handleAuthenticationException(
exception: AuthenticationException,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.dobby.backend.presentation.api.dto.request

data class DiscordMessageRequest(
val content: String? = null,
val embeds: List<Embed>? = null
) {

data class Embed(
val title: String? = null,
val description: String? = null
)
}
5 changes: 4 additions & 1 deletion src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,7 @@ cloud:
static: ${S3_REGION}
credentials:
access-key: ${S3_ACCESS_KEY}
secret-key: ${S3_SECRET_KEY}
secret-key: ${S3_SECRET_KEY}

discord:
webhook-url: ${DISCORD_WEBHOOK_URL}
3 changes: 3 additions & 0 deletions src/main/resources/template-application-local.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,6 @@ cloud:
credentials:
access-key: ${S3_ACCESS_KEY}
secret-key: ${S3_SECRET_KEY}

discord:
webhook-url: ${DISCORD_WEBHOOK_URL}
3 changes: 3 additions & 0 deletions src/test/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,6 @@ cloud:
credentials:
access-key: test
secret-key: test

discord:
webhook-url: test

0 comments on commit bdb301c

Please sign in to comment.