개발이야기/코틀린
아르메리아(Armeria) - ExceptionHandler
대머리개발자
2024. 1. 3. 16:16
728x90
어노테이션을(@)을 이용해서 간단하게 적용할 수 있다.
import com.linecorp.armeria.server.annotation.*
@RestController
@ExceptionHandler(DefinedExceptionHandler::class)
@PathPrefix("/codes")
class CodeEndPoint @Autowired constructor(var codeService: CodeService){
@ProducesJson
@Get("/{codes}")
@Description("쿠폰 발행")
fun publishCodes(@Param("codes") @Description("쿠폰 코드")codes:String): Mono<ApiResponse> {
return codeService.publishCodes(codes)
}
...
}
ExceptionHandler는 ExceptionHandlerFunction을 구현하면 된다.
class DefinedExceptionHandler : ExceptionHandlerFunction {
override fun handleException(ctx: ServiceRequestContext, req: HttpRequest, cause: Throwable): HttpResponse {
val gson = Gson()
val mutableMap = mapOf(
"code" to "PRO500",
"message" to cause.message,
)
return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR, MediaType.JSON_UTF_8,
gson.toJson(mutableMap)
)
}
}
★전역으로 예외를 기술하는 이유는 내가 정의된 예외 말고 시스템에서 발생하는 오류를 한방에 이쁘게 처리하기 위함이다. ★
: 전역으로 처리 하지 않았을 경우는 내부 오류를 그대로 노출 된다. why? 예외를 처리 못했으니.
: 전역처리를 하면 예상하지 못한 오류를 catch해서 이쁘게 노출할 수 있다.
물론 내가 예상한 예외는 별도로 정의를 해두고 쓰고 있다.
그 외 예기치 못한 상황에서 발생되는 친구들은 전역에서 "PRO500"으로 퉁 친다.
...
fun duplicateError(msg:String): Mono<ApiResponse>
= Mono.just(ApiResponse(code = "PRO0200", message = "It is duplicate.($msg)"))
fun alreadyIssuedError(): Mono<ApiResponse>
= Mono.just(ApiResponse(code = "PRO0201", message = "This code has already been issued."))
fun invalidError(msg:String): Mono<ApiResponse>
= Mono.just(ApiResponse(code = "PRO0300", message = "It is not valid.($msg)"))
...
728x90