Skip to content

Commit

Permalink
Discord 전송, 에러 핸들링
Browse files Browse the repository at this point in the history
  • Loading branch information
hhhello0507 committed Jan 6, 2025
1 parent fcb0893 commit 5693e9c
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.ohayo.moyamoya.global

import com.ohayo.moyamoya.infra.DiscordErrorSendService
import mu.KLogger
import org.springframework.core.env.Environment
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.HttpRequestMethodNotSupportedException
Expand All @@ -16,7 +18,9 @@ class CustomException(

@RestControllerAdvice
class CustomExceptionHandler(
private val logger: KLogger
private val logger: KLogger,
private val environment: Environment,
private val discordErrorSendService: DiscordErrorSendService
) {
@ExceptionHandler(CustomException::class)
fun handleCustomException(exception: CustomException): ResponseEntity<ErrorRes> {
Expand Down Expand Up @@ -48,6 +52,11 @@ class CustomExceptionHandler(
@ExceptionHandler(Exception::class)
fun handleException(exception: Exception, webRequest: WebRequest): ResponseEntity<ErrorRes> {
logger.error("CustomExceptionHandler.Exception", exception)

if (environment.activeProfiles.contains("prd")) {
discordErrorSendService.sendDiscordAlarm(exception, webRequest)
}

return createErrorResponse(
status = HttpStatus.INTERNAL_SERVER_ERROR,
message = HttpStatus.INTERNAL_SERVER_ERROR.reasonPhrase,
Expand All @@ -58,6 +67,7 @@ class CustomExceptionHandler(
status: HttpStatus,
message: String,
) = ResponseEntity.status(status).body(

ErrorRes(
status = status.value(),
message = message
Expand Down
39 changes: 39 additions & 0 deletions src/main/kotlin/com/ohayo/moyamoya/global/ErrorResponseSender.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.ohayo.moyamoya.global

import com.fasterxml.jackson.databind.ObjectMapper
import jakarta.servlet.http.HttpServletResponse
import mu.KLogger
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.stereotype.Component
import java.io.IOException

@Component
class ErrorResponseSender(
private val objectMapper: ObjectMapper,
private val logger: KLogger
) {

fun send(response: HttpServletResponse, customException: CustomException) =
send(response, customException.status, customException.message)

fun send(response: HttpServletResponse, status: HttpStatus, message: String? = null) {
try {
response.apply {
this.status = status.value()
contentType = MediaType.APPLICATION_JSON_VALUE
characterEncoding = "UTF-8"
}
response.writer.write(
objectMapper.writeValueAsString(
ErrorRes(
status = status.value(),
message = message ?: status.reasonPhrase
)
)
)
} catch (e: IOException) {
logger.error("ErrorResponseSender.send", e)
}
}
}
29 changes: 29 additions & 0 deletions src/main/kotlin/com/ohayo/moyamoya/global/HttpExceptionFilter.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.ohayo.moyamoya.global

import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.HttpStatus
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.stereotype.Component
import org.springframework.web.HttpRequestMethodNotSupportedException
import org.springframework.web.filter.OncePerRequestFilter

@Component
class HttpExceptionFilter(
private val sender: ErrorResponseSender
): OncePerRequestFilter() {
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain
) {
try {
filterChain.doFilter(request, response)
} catch (e: HttpRequestMethodNotSupportedException) {
sender.send(response = response, status = HttpStatus.METHOD_NOT_ALLOWED)
} catch (e: HttpMessageNotReadableException) {
sender.send(response = response, status = HttpStatus.BAD_REQUEST)
}
}
}
16 changes: 11 additions & 5 deletions src/main/kotlin/com/ohayo/moyamoya/global/SecurityConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,21 @@ package com.ohayo.moyamoya.global

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpStatus
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.web.DefaultSecurityFilterChain
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource

@Configuration
@EnableWebSecurity
class SecurityConfig {
class SecurityConfig(
private val httpExceptionFilter: HttpExceptionFilter,
private val sender: ErrorResponseSender
) {
@Bean
fun securityFilterChain(http: HttpSecurity): DefaultSecurityFilterChain = http
.cors { corsConfigurationSource() }
Expand All @@ -27,10 +32,11 @@ class SecurityConfig {
).permitAll()
.anyRequest().authenticated()
}
// .exceptionHandling {
// it.authenticationEntryPoint { _, response, _ -> sender.send(response, HttpStatus.UNAUTHORIZED) }
// it.accessDeniedHandler { _, response, _ -> sender.send(response, HttpStatus.FORBIDDEN) }
// }
.addFilterBefore(httpExceptionFilter, UsernamePasswordAuthenticationFilter::class.java)
.exceptionHandling {
it.authenticationEntryPoint { _, response, _ -> sender.send(response, HttpStatus.UNAUTHORIZED) }
it.accessDeniedHandler { _, response, _ -> sender.send(response, HttpStatus.FORBIDDEN) }
}
.build()

@Bean
Expand Down
6 changes: 3 additions & 3 deletions src/main/kotlin/com/ohayo/moyamoya/infra/Discord.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class DiscordErrorSendService(
.retrieve()
}

fun createMessage(e: Exception, request: WebRequest): DiscordMessage {
private fun createMessage(e: Exception, request: WebRequest): DiscordMessage {
return DiscordMessage(
content = "# \uD83D\uDEA8 에러 발생",
embeds = listOf(
Expand All @@ -53,7 +53,7 @@ class DiscordErrorSendService(

}

fun createRequestFullPath(webRequest: WebRequest): String {
private fun createRequestFullPath(webRequest: WebRequest): String {
val request = (webRequest as ServletWebRequest).request
var fullPath = "${request.method} ${request.requestURL}"

Expand All @@ -65,7 +65,7 @@ class DiscordErrorSendService(
return fullPath
}

fun getStackTrace(e: Exception): String = StringWriter().apply {
private fun getStackTrace(e: Exception): String = StringWriter().apply {
e.printStackTrace(PrintWriter(this))
}.toString()
}

0 comments on commit 5693e9c

Please sign in to comment.