Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can return my custom json file instead of default json file that generates spring boot?

I have a rest controller for authorization:

@RestController
class AuthController {

    @PostMapping("/sign-up")
    fun signUp(@RequestBody signUpRequest: SignUpRequest): ResponseEntity<String> {
       some code here..
    }
}

The signUp method gets SignUpRequest model as a request body. SignUpRequest model is:

enum class Role {
    @JsonProperty("Student")
    STUDENT,
    @JsonProperty("Tutor")
    TUTOR
}

data class SignUpRequest(
    val role: Role,
    val email: String,
    val password: String
)

When I make /sign-up post request with JSON:

{
    "role": "asdf",
    "email": "",
    "password": ""
}

It returns me an answer that were generated by spring boot:

{
    "timestamp": "2020-02-12T05:45:42.387+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "JSON parse error: Cannot deserialize value of type `foo.bar.xyz.model.Role` from String \"asdf\": not one of the values accepted for Enum class: [Student, Tutor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `foo.bar.xyz.model.Role` from String \"asdf\": not one of the values accepted for Enum class: [Student, Tutor]\n at [Source: (PushbackInputStream); line: 3, column: 10] (through reference chain: foo.bar.xyz.model.SignUpRequest[\"role\"])",
    "path": "/sign-up"
}

Question is: How I can return my custom JSON instead of that default generated JSON?

I want to return my custom JSON, like:

{
  "result": "Invalid user data are given",
  "errors": [
    {
      "fieldName": "ROLE",
      "text": "Given role does not exist"
    },
    {
      "fieldName": "EMAIL",
      "text": "EMAIL is empty"
    }
  ]
}
like image 758
Seydazimov Nurbol Avatar asked Oct 25 '25 06:10

Seydazimov Nurbol


2 Answers

I suggest you to create ErrorContrller that generates custom json map as response. Then when you will catch an error in sign-up method, call ErrorContrllers method. You can find info from this link

like image 188
alikhan Avatar answered Oct 26 '25 20:10

alikhan


Finally I found out a solution. You should create a class that annotates @ControllerAdvice, and make a method that annotates @ExceptionHandler.

@ControllerAdvice
class HttpMessageNotReadableExceptionController {

    @ExceptionHandler(HttpMessageNotReadableException::class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    fun handleException(
        exception: HttpMessageNotReadableException
    ): PostSignUpResponseError {

        val errors = mutableListOf<PostSignUpResponseErrorItem>()

        errors.add(
            PostSignUpResponseErrorItem(
                fieldNamePost = "Role",
                text = "Given role does not exist"
            )
        )

        return PostSignUpResponseError(
            result = "Invalid user data are given",
            errors = errors
        )
    }
}

where PostSignUpResponseErrorItem and PostSignUpResponseError are:

data class PostSignUpResponseError(
    val result: String,
    val errors: List<PostSignUpResponseErrorItem>
)

class PostSignUpResponseErrorItem(
    val fieldNamePost: PostSignUpRequestFieldName,
    val text: String
)

Anyway, I still don't know how to attach this thing to a certain PostMapping method.

like image 20
Seydazimov Nurbol Avatar answered Oct 26 '25 19:10

Seydazimov Nurbol