Sojan
Sojan

Reputation: 47

How to remove _links object from Micronaut JSON error response

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

Upvotes: 0

Views: 375

Answers (1)

ShingJo
ShingJo

Reputation: 664

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"))))

}

Upvotes: 1

Related Questions