java - How to throw Spring @Valid "exception"?
问题描述
I'm using Spring to build my REST api. One of my methods is decorated with @Valid. This produces a JSON that looks like this:
{
"timestamp": "2019-11-04T19:07:08.387+0000",
"status": 400,
"error": "Bad Request",
"errors": [
{
"codes": [
"NotNull.customer.firstName",
"NotNull.firstName",
"NotNull.java.lang.String",
"NotNull"
],
"arguments": [
{
"codes": [
"customer.firstName",
"firstName"
],
"arguments": null,
"defaultMessage": "firstName",
"code": "firstName"
}
],
"defaultMessage": "must not be null",
"objectName": "customer",
"field": "firstName",
"rejectedValue": null,
"bindingFailure": false,
"code": "NotNull"
}
],
"message": "Validation failed for object='customer'. Error count: 1",
"path": "/customers"
}
Doing a Google search, to produce a HTTP 400 error, I'm supposed to throw ResponseStatusException(HttpStatus.BAD_REQUEST);
This produces a JSON like this:
{
"timestamp": "2019-11-04T19:08:02.408+0000",
"status": 400,
"error": "Bad Request",
"message": "400 BAD_REQUEST",
"path": "/customers"
}
The message is easy to change obviously, but I'm more asking about how to get the Errors array. That doesn't seem to be in ResponseStatusException?
I can recreate it pretty easily, but I was hoping there was one built already?
EDIT: This isn't input validation per say... this is throwing an error FOR the input, but I need to hit the database first to do the actual validation, so that part is in my service layer and throws an internal exception if it isn't valid.
解决方案
如果您使用的是验证器,那么您可以使用配置文件来自定义错误,例如validator.properties
推荐阅读
- javascript - forEach js,选择数组中的对象?
- amazon-web-services - 创建 Fargate 配置文件失败
- python-requests - 将发布资产上传到 Github 会损坏文件
- duplicates - Power Query 中删除重复项的顺序是什么?
- python - 由于 PyQt5,Spyder 的环境变量崩溃
- asp.net-mvc - Syncfusion Asp.Net Datagrid:如何从 CRUD 类返回错误
- berkshelf - berkshelf 无法解决链式 git 依赖
- github - hyperledger-fabric-readthedocs.io 教程,开发人员的链代码,找不到包 shim - 已修复
- django - Django登录方法给出递归错误
- bash - 基于时间值的分片 CSV