简体   繁体   English

处理Ratpack Context.parse执行

[英]Handling Ratpack Context.parse execptions

I'm writing an API in Kotlin with the Ratpack framework, using Jackson to deserialize JSON request bodies. 我正在使用Ratpack框架在Kotlin中编写一个API,使用Jackson来反序列化JSON请求主体。 When I send an invalid request body, my application throws a 500 internal server error exception: 当我发送无效的请求正文时,我的应用程序引发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)

The exception when this endpoint is hit with an invalid request body is: 当此端点被无效的请求正文击中时,异常是:

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

I have a generic error handler which checks the type of Exception thrown, and returns an appropriate status. 我有一个通用的错误处理程序,用于检查引发的Exception类型,并返回适当的状态。 But in this case, checking for a MissingKotlinParameterException and returning 400 bad request does not make sense, because this exception may be thrown in other circumstances. 但是在这种情况下,检查MissingKotlinParameterException并返回400错误请求是没有意义的,因为在其他情况下可能会抛出此异常。

Additionally, I could add onError after the ctx.parse line, but this is going to be a large API, and implementing that in every handler doesn't follow the pattern of having a generic error handler to keep the API consistent. 另外,我可以在ctx.parse行之后添加onError,但这将是一个很大的API,并且在每个处理程序中实施该操作都不遵循具有通用错误处理程序以保持API一致的模式。 Is there a way to get Ratpack to throw a specific exception (something like ParseFailedException ) when the parse fails, so that I can catch it and return a 400 bad request? 当解析失败时,是否有办法让ParseFailedException抛出特定的异常(类似于ParseFailedException ),以便我可以捕获它并返回400错误的请求?

As a workaround I've written an extension method: 作为解决方法,我编写了一个扩展方法:

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

Where my generic error handler catches the BadRequestException, and sets the response status to 400 我的通用错误处理程序在其中捕获BadRequestException,并将响应状态设置为400

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM