mirror of
https://github.com/Dannecron/spring-boot-demo.git
synced 2025-12-26 08:42:33 +03:00
add global exception handler for controllers
add new not found exception, add new test for ShopController
This commit is contained in:
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.example.demo.exceptions
|
||||
|
||||
class NotFoundException: RuntimeException()
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.example.demo.responses
|
||||
|
||||
class BaseResponse(val status: ResponseStatus)
|
||||
|
||||
fun makeNotFound(): BaseResponse = BaseResponse(status = ResponseStatus.NOT_FOUND)
|
||||
@@ -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");
|
||||
}
|
||||
Reference in New Issue
Block a user