如何从Micronaut JSON错误响应中删除_links对象

huangapple go评论70阅读模式
英文:

How to remove _links object from Micronaut JSON error response

问题

我正在开发 Micronaut Kotlin 应用程序。
只有在 API 成功时一切正常运行。

但是,当 API 遇到任何异常时,它的响应主体包含了不在我这种情况下所需的 _links 对象。

对于 404 未找到异常,在 Postman 中会抛出以下异常:

{
    "message": "Not Found",
    "_embedded": {
        "errors": [
            {
                "message": "User Id not found."
            }
        ]
    },
    "_links": {
        "self": {
            "href": "/v1/getUser?userId=1234",
            "templated": false
        }
    }
}

以下是我的控制器代码:

@Get(GET_USER, produces = [MediaType.APPLICATION_JSON], consumes = [MediaType.APPLICATION_JSON])
@Operation(summary = "Gets the User from the Database.")
@ApiResponses(
    ApiResponse(responseCode = "200", description = "ok"),
    ApiResponse(
        responseCode = "500",
        description = "Internal Server Error: Sessions are not supported by the MongoDB cluster to which this client is connected"
    ),
    ApiResponse(responseCode = "400", description = "Bad Request: User Id is empty"),
    ApiResponse(responseCode = "404", description = "Not Found")
)
@Status(HttpStatus.OK)
suspend fun getUser(
    @NotBlank userId: String
): User? {
    return withContext(Dispatchers.IO) {
        userService.getUser(userId)
    }
}

以下是我的服务:

fun getUser(userId: String): User {
    try {
        val result = userRepo.findByUserIdEquals(userId)
        if (result != null) {
            return result
        } else {
            throw HttpStatusException(
                HttpStatus.NOT_FOUND,
                "User Id not found."
            )
        }
    } catch (ex: Exception) {
        throw ex
    }
}

以下是我的存储库:

@MongoRepository
interface UserRepo : CoroutineCrudRepository<User, String> {
    @MongoFindQuery("{userId: :userId}")
    fun findByUserIdEquals(userId: String): User?
}

这是我的用户模型:

@MappedEntity
@Introspected
data class User(
    @field: Id
    @field: GeneratedValue
    val mongoDocId: String? = null,
    @field: NotNull
    @field: NotBlank
    @field: NotEmpty
    @field: Size(min = 1, max = 10, message = "userId must in between 1 and 15 characters")
    val userId: String,
    @field: NotNull
    @field: NotBlank
    @field: NotEmpty
    val code: String
)

我还在 build.gradle 文件中添加了以下依赖项:

annotationProcessor("io.micronaut:micronaut-inject-java")
kapt("io.micronaut:micronaut-inject-java")

是否有配置来移除 _links 对象,或者是否需要编写任何代码来移除它?

非常感谢您的帮助。

英文:

I am working on Micronaut Kotlin application.
Everything works as expected as long as the API is successful.

But when the API encounters any exception,then the response body of it is containing the _links object which is not required in my case.

For a 404 not found exception, it is throwing exception like below in postman

{
&quot;message&quot;: &quot;Not Found&quot;,
&quot;_embedded&quot;: {
    &quot;errors&quot;: [
        {
            &quot;message&quot;: &quot;User Id not found.&quot;
        }
    ]
},
&quot;_links&quot;: {
    &quot;self&quot;: {
        &quot;href&quot;: &quot;/v1/getUser?userId=1234&quot;,
        &quot;templated&quot;: false
    }
}
}

Here is my controller code below:

@Get(GET_USER, produces = [MediaType.APPLICATION_JSON], consumes = [MediaType.APPLICATION_JSON])
@Operation(summary = &quot;Gets the User from the Database.&quot;)
@ApiResponses(
    ApiResponse(responseCode = &quot;200&quot;, description = &quot;ok&quot;),
    ApiResponse(
        responseCode = &quot;500&quot;,
        description = &quot;Internal Server Error: Sessions are not supported by the MongoDB cluster to which this client is connected&quot;
    ),
    ApiResponse(responseCode = &quot;400&quot;, description = &quot;Bad Request: User Id is empty&quot;),
    ApiResponse(responseCode = &quot;404&quot;, description = &quot;Not Found&quot;)
)
@Status(HttpStatus.OK)
suspend fun getUser(
    @NotBlank userId: String
): User? {
    return withContext(Dispatchers.IO) {
        userService.getUser(userId)
    }
}

Here is my Service:

fun getUser(userId: String): User {
    try {
        val result = userRepo.findByUserIdEquals(userId)
        if (result != null) {
            return result
        } else {
            throw HttpStatusException(
                HttpStatus.NOT_FOUND,
                &quot;User Id not found.&quot;
            )
        }
    } catch (ex: Exception) {
        throw ex
    }
}

Here is my Repo

@MongoRepository
interface UserRepo : CoroutineCrudRepository&lt;User, String&gt; {
    @MongoFindQuery(&quot;{userId: :userId}&quot;)
    fun findByUserIdEquals(userId: String): User?
}

This is my user model

@MappedEntity
@Introspected
data class User(
    @field: Id
    @field: GeneratedValue
    val mongoDocId: String? = null,
    @field: NotNull
    @field: NotBlank
    @field: NotEmpty
    @field: Size(min = 1, max = 10, message = &quot;userId must in between 1 and 15 characters&quot;)
    val userId: String,
    @field: NotNull
    @field: NotBlank
    @field: NotEmpty
    val code: String
)

I also added below to my dependencies in build.gradle file

annotationProcessor(&quot;io.micronaut:micronaut-inject-java&quot;)
kapt(&quot;io.micronaut:micronaut-inject-java&quot;)

Is there any configuration to remove the _links object or do i need to code anything for removing it.

Any help is appreciated

答案1

得分: 1

查看 错误处理 文档。

例如:

data class User(val id: Long, val name: String)

@Controller
class MyController {

    @Get("/{userId}")
    fun getUser(userId: Long): User? {
        return if (userId < 10) {
            User(userId, "User $userId")
        } else {
            null // 返回 null 触发 notFound()
        }
    }

    @Error(status = HttpStatus.NOT_FOUND)
    fun notFound(): HttpResponse<JsonError> =
        HttpResponse.notFound<JsonError>()
            .body(JsonError("Not Found")
                .embedded("errors", listOf(JsonError("User Id not found"))))

}
英文:

See documentation on error handling.

For example:

data class User(val id: Long, val name: String)

@Controller
class MyController {

    @Get(&quot;/{userId}&quot;)
    fun getUser(userId: Long) : User? {
        return if(userId &lt; 10) {
            User(userId, &quot;User $userId&quot;)
        } else {
            null // Returning null triggers notFound()
        }
    }

    @Error(status = HttpStatus.NOT_FOUND)
    //fun notFound(request: HttpRequest&lt;*&gt;) //If you need the request
    fun notFound(): HttpResponse&lt;JsonError&gt; =
        HttpResponse.notFound&lt;JsonError&gt;()
            .body(JsonError(&quot;Not Found&quot;)
                .embedded(&quot;errors&quot;, listOf(JsonError(&quot;User Id not found&quot;))))

}

huangapple
  • 本文由 发表于 2023年6月12日 21:02:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76456942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定