This is the first day of my participation in Gwen Challenge

Since the previous Django was not normalized. The verification information returned to the front end is messy, and now there is a chance to reconstruct, so I want to normalize the error information again.

Let’s make a data class

// Response.kt
// Encapsulates the interface's unified return entity class
data class Response<T>(
    val code: Int = 200.val data: T? = null.val msg: String? = "Request successful".val err: HashMap<String, String>? = null
)
Copy the code

Encapsulate a checksum exception class

Next we use the @ControllerAdvice annotation and the @validexception annotation

// ValidParamException.kt
package com.demo.utils

import org.springframework.stereotype.Controller
import org.springframework.validation.BindingResult
import org.springframework.validation.FieldError
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody
import java.util.HashMap

/ * * *@author watson haw
 * @date2021/6/1 8:28pm */

@Controller
@ControllerAdvice
class ValidParamException {
    @ExceptionHandler(value = [(MethodArgumentNotValidException::class)])
    @ResponseBody
    fun handleMethodArgumentNotValidException(ex: MethodArgumentNotValidException): Response<HashMap<String, String>> {
        val bindingResult: BindingResult = ex.bindingResult
        val errors: List<FieldError> = bindingResult.fieldErrors
        val errorMessage = HashMap<String, String>(errors.size)
        for (error: FieldError in errors) {
            DefaultMessage does not necessarily return a value
            // The next iteration is performed only when there is a return value
            error.defaultMessage?.let { errorMessage.put(error.field, it) };
        }
        // The data defined above will be used as Result
        // But note that code 404 does not change the status returned to the front end, just for status determination
        return Response(404, err = errorMessage)
    }
}
Copy the code

The result is shown below, so that the front end can retrieve the value from err when code is 400 and return the corresponding error.

Difficulties encountered

Java direct reflection is acceptable

@ExceptionHandler(MethodArgumentNotValidException.class)

But in Kotlin we need to put the concretely reflected class as a value in the collection

@ExceptionHandler(value = [(MethodArgumentNotValidException::class)])

In Java, you can use HashMap<String, String>.

But in Kotlin you need to call a native Java collection, which is not very Kotlin, so you can use mapOf or hashMapOf instead, and we’ll do that later.

Refer to the article

Kotlin – Spring REST – ControllerAdvice with ExceptionHandler won’t get invoked

@controlleradvice @valid Implements intercepting error messages in response to JSON for front-end parameter validation