kotlin使用spring mvc(六)

使用@RestControllerAdvice擴展參數驗證java

在上一節中我看能夠看到參數驗證返回的錯誤信息以下post

{
	"timestamp": "2018-10-25T06:44:31.196+0000",
	"status": 400,
	"error": "Bad Request",
	"errors": [{
		"codes": ["NotEmpty.passenger.name", "NotEmpty.name", "NotEmpty.java.lang.String", "NotEmpty"],
		"arguments": [{
			"codes": ["passenger.name", "name"],
			"arguments": null,
			"defaultMessage": "name",
			"code": "name"
		}],
		"defaultMessage": "用戶名不能爲空",
		"objectName": "passenger",
		"field": "name",
		"rejectedValue": "",
		"bindingFailure": false,
		"code": "NotEmpty"
	}],
	"message": "Validation failed for object='passenger'. Error count: 1",
	"path": "/p/add"
}

事實上咱們想要的只是code

{"data":null,"succes":false,"msg":"用戶名不能爲空"}

那麼咱們就應該捕捉到參數驗證異常以後,返回CommonResult對象對象

@RestControllerAdvice
class GlobalExcpetionHandler{
    //驗證參數
    @ExceptionHandler(value = [MethodArgumentNotValidException::class])
    fun validParameters(e:MethodArgumentNotValidException):CommonResult<Any>{
        return CommonResult(null,false,e.bindingResult.allErrors.firstOrNull()?.defaultMessage ?: "")
    }
}

再次post請求過來,發現咱們設置的捕捉異常已經生效了io

相關文章
相關標籤/搜索