【问题标题】:Exception handling in MicronautMicronaut 中的异常处理
【发布时间】:2021-06-07 05:42:36
【问题描述】:

micronaut 有没有办法抛出异常来指定响应的错误代码,就像我们在 springboot 中可以做的一样:

throw new ResponseStatusException(HttpStatus.FORBIDDEN)

还是我们总是必须实现自己的异常处理程序?

我宁愿不必为了能够返回 400 或 403 响应而实现异常处理程序。

【问题讨论】:

  • 你在使用 Micronaut 安全库吗?
  • 如果你的控制器返回 HttpResponse,你可以只返回一个 HttpResponse 403。但是最好有处理特定异常的处理程序。
  • @JeffScottBrown 不,尚未使用安全库。只是迈出了第一步来了解它是如何工作的。
  • @Anorgar 我会尝试一下,谢谢。
  • 目前还不清楚您要在什么情况下执行此操作。 docs.micronaut.io/2.4.0/api/io/micronaut/http/exceptions/… 可能是相关的。

标签: java spring-boot kotlin micronaut


【解决方案1】:

我想要的课程是:

io.micronaut.http.exceptions.HttpStatusException

一开始没找到是因为缺少依赖:

implementation("io.micronaut:micronaut-http")

在本例中,我使用它成功地返回了带有消息的 404 错误:

fun findById(id: Long): User {
    val user = userRepository.findById(id)
    return if (user.isPresent()) user.get() else throw HttpStatusException(HttpStatus.NOT_FOUND, "User not found")
}

如果这是不错的 kotlin 代码,请随时发表评论。我对 kotlin 很陌生,来自 java 和 scala 背景。对我来说看起来不错xD

【讨论】:

  • 您的 DAO/存储库可能不应该返回 HTTP 异常
【解决方案2】:

只有一个技巧,如果你想避免 return 语句,你可以更新你的方法以使用“kotlin full powers”

类似这样的:

fun findById(id: Long): User = 
    userRepository.findById(id)
        ?.let { it.orElseThrow(HttpStatusException(HttpStatus.NOT_FOUND, "User not found"))}

这是 safe-call operator 和转换方法 let 的用途,它们可以获取您的实体,如果找不到则抛出异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2020-06-26
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多