0

我正在使用 Ratpack 框架在 Kotlin 中编写一个 API,使用 Jackson 来反序列化 JSON 请求主体。当我发送无效的请求正文时,我的应用程序会引发 500 内部服务器错误异常:

import com.google.inject.Inject
import com.mycompany.mynamespace.MyComponent
import ratpack.func.Action
import ratpack.handling.Chain
import java.util.UUID

class MyTestEndpoint @Inject constructor(
    private val myComponent: MyComponent) : Action<Chain> {

  override fun execute(chain: Chain) {
    chain
        .post { ctx ->
          ctx.parse(MyParams::class.java)
              .map { parsedObject -> myComponent.process(parsedObject) }
              .then { ctx.response.send() }
        }
  }
}

data class MyParams(val borrowingId: UUID)

此端点被无效请求正文命中时的异常是:

com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException: Instantiation of [simple type, class com.mycompany.mynamespace.MyParams] value failed for JSON property borrowingId due to missing (therefore NULL) value for creator parameter borrowingId which is a non-nullable type

我有一个通用错误处理程序,它检查抛出的异常类型,并返回适当的状态。但是在这种情况下,检查 MissingKotlinParameterException 并返回 400 bad request 没有意义,因为在其他情况下可能会抛出此异常。

此外,我可以在 ctx.parse 行之后添加 onError,但这将是一个大型 API,并且在每个处理程序中实现它并不遵循具有通用错误处理程序以保持 API 一致的模式。有没有办法让 Ratpack 在解析失败时抛出特定异常(类似于ParseFailedException),以便我可以捕获它并返回 400 错误请求?

4

1 回答 1

0

作为一种解决方法,我编写了一个扩展方法:

fun <T: Any> Context.tryParse(type: Class<T>): Promise<T> {
    return parse(type)
        .onError { ex -> throw BadRequestException(ex) }
}

我的通用错误处理程序捕获 BadRequestException,并将响应状态设置为 400

于 2018-08-23T15:06:02.077 回答