Why Kotlin receives such an UndeclaredThrowableException rather than a ParseException?

前端 未结 2 1503
生来不讨喜
生来不讨喜 2021-02-19 06:32

I have an extension method that converts string to Date in Kotlin.

fun String.convertToDate() : Date {
  var pattern: String = \"dd-mm-yyyy\"
  val         


        
2条回答
  •  广开言路
    2021-02-19 07:17

    It seems that your service is running in a different invocation context than your controller. As the service is throwing the exception you cannot catch it in the controller; it looks like you're calling the service directly, but due to code injection you really aren't. So what happens is that the invocation context (usually a thread) ends with an exception. This gets translated into a UndeclaredThrowableException with the original exception as cause.

    There are two ways of dealing with this:

    1. catch the exception locally in the service where the exception is generated;
    2. catch the UndeclaredThrowableException in a separate try/catch and then re-throw the cause.

    The first option should be preferred but requires you to handle the exception in the service. The second one looks too much like a hack to me, but it doesn't require setting up the exception handling in the service instead of the controller.

提交回复
热议问题