72 lines
2.4 KiB
Kotlin
72 lines
2.4 KiB
Kotlin
package com.android.trisolarisserver.config
|
|
|
|
import jakarta.servlet.http.HttpServletRequest
|
|
import org.springframework.http.HttpStatus
|
|
import org.springframework.http.ResponseEntity
|
|
import org.springframework.security.access.AccessDeniedException
|
|
import org.springframework.web.bind.annotation.ExceptionHandler
|
|
import org.springframework.web.bind.annotation.RestControllerAdvice
|
|
import org.springframework.web.server.ResponseStatusException
|
|
import java.time.OffsetDateTime
|
|
|
|
@RestControllerAdvice
|
|
class ApiExceptionHandler {
|
|
|
|
@ExceptionHandler(ResponseStatusException::class)
|
|
fun handleResponseStatus(
|
|
ex: ResponseStatusException,
|
|
request: HttpServletRequest
|
|
): ResponseEntity<ApiError> {
|
|
val status = ex.statusCode as HttpStatus
|
|
return ResponseEntity.status(status).body(
|
|
ApiError(
|
|
timestamp = OffsetDateTime.now().toString(),
|
|
status = status.value(),
|
|
error = status.reasonPhrase,
|
|
message = ex.reason ?: "Request failed",
|
|
path = request.requestURI
|
|
)
|
|
)
|
|
}
|
|
|
|
@ExceptionHandler(AccessDeniedException::class)
|
|
fun handleAccessDenied(
|
|
ex: AccessDeniedException,
|
|
request: HttpServletRequest
|
|
): ResponseEntity<ApiError> {
|
|
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(
|
|
ApiError(
|
|
timestamp = OffsetDateTime.now().toString(),
|
|
status = HttpStatus.FORBIDDEN.value(),
|
|
error = HttpStatus.FORBIDDEN.reasonPhrase,
|
|
message = ex.message ?: "Forbidden",
|
|
path = request.requestURI
|
|
)
|
|
)
|
|
}
|
|
|
|
@ExceptionHandler(Exception::class)
|
|
fun handleGeneric(
|
|
ex: Exception,
|
|
request: HttpServletRequest
|
|
): ResponseEntity<ApiError> {
|
|
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
|
|
ApiError(
|
|
timestamp = OffsetDateTime.now().toString(),
|
|
status = HttpStatus.INTERNAL_SERVER_ERROR.value(),
|
|
error = HttpStatus.INTERNAL_SERVER_ERROR.reasonPhrase,
|
|
message = ex.message ?: "Internal server error",
|
|
path = request.requestURI
|
|
)
|
|
)
|
|
}
|
|
}
|
|
|
|
data class ApiError(
|
|
val timestamp: String,
|
|
val status: Int,
|
|
val error: String,
|
|
val message: String,
|
|
val path: String
|
|
)
|