Hello, I am trying to implement a global exception...
# server
k
Hello, I am trying to implement a global exception handler in spring boot kotlin, here is my code
Copy code
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler



@ControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(Exception::class)
    fun handleGenericException(ex: Exception): ResponseEntity<Any> {
        val errorMessage = "An unexpected error occurred: ${ex.message}"
        return ResponseEntity(errorMessage, HttpStatus.INTERNAL_SERVER_ERROR)
    }

    @ExceptionHandler(value = [ArithmeticException::class])
    fun handleArithmeticException(ex: ArithmeticException): ResponseEntity<Any> {
        val errorMessage = "An arithmetic error occurred: ${ex.message}"
        return ResponseEntity(errorMessage, HttpStatus.INTERNAL_SERVER_ERROR)
    }

    @ExceptionHandler(RuntimeException::class)
    fun handleRuntimeException(exception: RuntimeException): ResponseEntity<Any> {
        return ResponseEntity
            .status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body("abc bab")
    }

}
Issue I am facing right now is that when i throw an exception in my controller, it is not invoking the GlobalExceptionHandler, here is the controller code.
Copy code
package com.example.balancesservice


import org.apache.http.HttpStatus
import org.springframework.http.HttpStatusCode
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.server.ResponseStatusException

@RestController
class HealthController {

    @GetMapping("/health")
    fun healthCheck(): String {
            throw Exception("Div by zero not all")

    }
}
Can anyone please guide?
not kotlin but kotlin colored 1
h
Hey man, how are you doing ? I can be wrong but I think all the exceptions caught by the global exception handler should be an inheritance from
RuntimeException
.
k
i am using @RestController throughout my app so changing the bean from @ControllerAdvice to @RestControllerAdvice solved the issue.
h
Nice