add global exception handler for controllers

add new not found exception, add new test for ShopController
This commit is contained in:
Denis Savosin
2024-09-25 16:55:24 +07:00
parent 61e5e7cea6
commit 6247eedb9a
6 changed files with 69 additions and 15 deletions

View File

@@ -1,11 +1,11 @@
package com.example.demo.controllers
import com.example.demo.exceptions.NotFoundException
import com.example.demo.provider.ShopProvider
import jakarta.servlet.http.HttpServletResponse
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.encodeToJsonElement
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController
@@ -16,14 +16,9 @@ class ShopController (
) {
@GetMapping(value = ["/shop/common-info"], produces = ["application/json"])
@ResponseBody
@Throws(NotFoundException::class)
fun commonInfo(response: HttpServletResponse): String {
val shop = shopProvider.getRandomShop()
if (shop == null) {
response.status = HttpStatus.NOT_FOUND.value()
return "not found"
}
val shop = shopProvider.getRandomShop() ?: throw NotFoundException()
return Json.encodeToJsonElement(value = mapOf(
"customers" to mapOf(

View File

@@ -0,0 +1,13 @@
package com.example.demo.exceptions
import com.example.demo.responses.makeNotFound
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
@ControllerAdvice
class ExceptionHandler {
@ExceptionHandler(NotFoundException::class)
fun handleNotFound(): ResponseEntity<Any> = ResponseEntity(makeNotFound(), HttpStatus.NOT_FOUND)
}

View File

@@ -0,0 +1,3 @@
package com.example.demo.exceptions
class NotFoundException: RuntimeException()

View File

@@ -0,0 +1,5 @@
package com.example.demo.responses
class BaseResponse(val status: ResponseStatus)
fun makeNotFound(): BaseResponse = BaseResponse(status = ResponseStatus.NOT_FOUND)

View File

@@ -0,0 +1,7 @@
package com.example.demo.responses
import com.fasterxml.jackson.annotation.JsonValue
enum class ResponseStatus(@JsonValue val status: String) {
NOT_FOUND("not found");
}