khan husnain
10/03/2023, 3:31 PMimport 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.
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?Higor Oliveira
10/04/2023, 3:48 PMRuntimeException
.khan husnain
10/04/2023, 3:49 PMHigor Oliveira
10/04/2023, 3:50 PM