如何在 Quarkus 中自定义未经授权的响应?

问题描述 投票:0回答:1

因为我们使用自定义错误格式,所以我们想要自定义所有错误响应...特别是禁止(我们成功)和未经授权(我们失败)。

我阅读了很多文档、帖子,并尝试了不同的解决方案,您可以在我的示例项目

中找到

第一个:ServerExceptionMapper

@ServerExceptionMapper
@Priority(1)
fun unauthorized(e: UnauthorizedException) =
   mapExceptionIntoError(Response.Status.UNAUTHORIZED, "UNAUTHORIZED", e.message)

第二:ExceptionMapper

@Provider
@Priority(Priorities.AUTHORIZATION)
class UnauthorizedErrorMapper : ExceptionMapper<UnauthorizedException> {

    private val logger: Logger = Logger.getLogger(this.javaClass.simpleName)

    @Override
    override fun toResponse(exception: UnauthorizedException): Response {
        logger.severe(exception.message)

        val message = exception.message
        val code = STATUS.statusCode
        val error =  ErrorInfo(STATUS.statusCode, STATUS.name, message)

        return Response
            .status(code)
            .entity(error)
            .build()
    }

    companion object {
        private val STATUS = Response.Status.UNAUTHORIZED
    }
}

第三:failureHandler

@ApplicationScoped
class UnauthorizedExceptionHandler {
    fun init(@Observes router: Router) {
        router.route().failureHandler { event ->
            if (event.failure() is UnauthorizedException) {
                event.response().end("CUSTOMIZED_RESPONSE")
            } else {
                event.next()
            }
        }
    }
}

没有成功。 我错过了什么或做错了什么?

提前致谢 帕特里斯

kotlin quarkus unauthorized quarkus-reactive
1个回答
0
投票

这个用例确实有效,因为我们在仓库中有一个 test 可以做到这一点。

public static final class CustomExceptionMappers {

    @ServerExceptionMapper(UnauthorizedException.class)
    public Response forbidden() {
        return Response.status(999).build();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.