Hi, i have Exceptions defined like this ```const v...
# spring
r
Hi, i have Exceptions defined like this
Copy code
const val reason = "store not found"
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = reason)
class StoreNotFoundException : RuntimeException()
but i want to log the error whenever its been throw
Copy code
const val reason = "store not found"
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = reason)
class StoreNotFoundException : RuntimeException(){
    init {
        warningLog(reason)
    }

    companion object {
        private val logger = LoggerFactory.getLogger(CustomException::class.java)
        fun warningLog(message: String) {
            logger.warn(message)
        }
    }
}
i've implemented like this Since i have a lot of exceptions defined like this and i want to have the log whenever one is threw, how can i generalize this behavior? how can i write a CustomException?
n
Ok I think you need to use ControllerAdvice and catch the exception there. After that you can log it and whatever you want to do with it.
r
yes, like this
Copy code
@PutMapping("/{id}")
fun updateStore(...): Store {
        ... ?: throw  StoreNotFoundException()
}
n
Oops accidentally edited the previous message. But ControllerAdvice is one way to do this I would say.
r
already tried lke this:
Copy code
try{
    ...
    throw StoreNotFoundException()
}catch(e: StoreNotFoundException){
    log("store not found throwed")
}
but doing this for every endpoint is a lot when the only thing that i want to do is log the Exception message if it happen
n
Ok I would do something like this collabedit.com/bt2t8
k
exceptionhandler is definately way to go
why should be exception responsible for logging?
😐 1
r
@kqr you right! 😅
thanks
Finally i solved my problem with this:
Copy code
@ControllerAdvice
class GlobalResponseException {
    @ExceptionHandler(RuntimeException::class)
    private fun handleRuntimeException(e: Exception) {
        ExceptionLogger.log("$e at ${e.stackTrace?.first()?.methodName} inside ${e.stackTrace?.first()?.fileName}")
    }
}

class ExceptionLogger {
    companion object {
        private val logger = LoggerFactory.getLogger(ExceptionLogger::class.java)
        fun log(message: String) = logger.warn(message)
    }
}
(if in the future someone has the same problem :3 ) like my Exceptions inherit from RuntimeException() it does everything i need