英文:
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
{
"message": "Not Found",
"_embedded": {
"errors": [
{
"message": "User Id not found."
}
]
},
"_links": {
"self": {
"href": "/v1/getUser?userId=1234",
"templated": false
}
}
}
Here is my controller code below:
@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)
}
}
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,
"User Id not found."
)
}
} catch (ex: Exception) {
throw ex
}
}
Here is my Repo
@MongoRepository
interface UserRepo : CoroutineCrudRepository<User, String> {
@MongoFindQuery("{userId: :userId}")
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 = "userId must in between 1 and 15 characters")
val userId: String,
@field: NotNull
@field: NotBlank
@field: NotEmpty
val code: String
)
I also added below to my dependencies in build.gradle file
annotationProcessor("io.micronaut:micronaut-inject-java")
kapt("io.micronaut:micronaut-inject-java")
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("/{userId}")
fun getUser(userId: Long) : User? {
return if(userId < 10) {
User(userId, "User $userId")
} else {
null // Returning null triggers notFound()
}
}
@Error(status = HttpStatus.NOT_FOUND)
//fun notFound(request: HttpRequest<*>) //If you need the request
fun notFound(): HttpResponse<JsonError> =
HttpResponse.notFound<JsonError>()
.body(JsonError("Not Found")
.embedded("errors", listOf(JsonError("User Id not found"))))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论