Warm tip: This article is reproduced from serverfault.com, please click

Raise error in case if json object has missing keys in post request

发布于 2020-11-28 12:54:08

I am sending a json in my post request. I want to raise an friendly error in case if any keys is missing.

@PostMapping("/copy")
    fun post(@RequestBody user: User): String {

        log.debug("Received a request")
        return "hello"
    }


data class User(
     val name: String,
     val age: Int
)

So my question is if I post a request and if post data like: {"age":23} then I get a response saying bad request "name is not defined".

Can anyone share some thoughts here? How should I handle such cases? I do not want to write if else in the post request as my data will be very big and there will be many keys which will be essential.

Questioner
Atya
Viewed
0
Hex 2020-11-29 00:55:44

I see. Try this:

@ExceptionHandler(HttpMessageNotReadableException::class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
fun handleError(exception: HttpMessageNotReadableException): String =
    exception.mostSpecificCause.message ?:exception.localizedMessage

Output should be as follow:

Parameter specified as non-null is null: method hex.adapter.Example$User., parameter name

To format it as ""name is not defined" you can write:

@ExceptionHandler(HttpMessageNotReadableException::class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
fun handleError(exception: HttpMessageNotReadableException): String =
     exception.mostSpecificCause.message
             ?.split("parameter ")
             ?.get(1)
             ?.let { "$it is not defined" }
             ?:exception.localizedMessage