Reputation: 24462
I have the following API definition:
@ResponseBody
@PostMapping(path = "/configureSection")
public ResponseEntity<ResultData> configureSegment(@RequestParam() String Section,
@RequestBody SectionConfig sectionConfig);
public class SegmentConfig {
@JsonProperty(value = "txConfig", required = true)
TelemetryConfig telemetryConfig;
@JsonProperty(value = "rxConfig")
ExternalConfig externalConfig;
}
I defined txConfig is required attribute (which is class), but when sending empty JSON ({}
) spring boot still runs the API while I expect it to return an error that parameter tsConfig was not set.
Any idea what I'm missing?
Edit: Using @Valid and @NotNull solved it, but the error returned is too informative, any way to fix it?
{
"timestamp": 1588753367913,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.MethodArgumentNotValidException",
"errors": [
{
"codes": [
"NotNull.segmentConfig.telemetryConfig",
"NotNull.telemetryConfig",
"NotNull.services.TelemetryConfig",
"NotNull"
],
"arguments": [
{
"codes": [
"segmentConfig.telemetryConfig",
"telemetryConfig"
],
"arguments": null,
"defaultMessage": "telemetryConfig",
"code": "telemetryConfig"
}
],
"defaultMessage": "Please provide a valid txConfig",
"objectName": "segmentConfig",
"field": "telemetryConfig",
"rejectedValue": null,
"bindingFailure": false,
"code": "NotNull"
}
],
"message": "Bad Request",
"path": "/mypath"
}`
Upvotes: 1
Views: 12651
Reputation: 1013
Use @Valid and @NotNull annotation to validate as below :-
@ResponseBody
@PostMapping(path = "/configureSection")
public ResponseEntity<ResultData> configureSegment(@RequestParam() String Section,
@RequestBody @Valid SectionConfig sectionConfig
) {
public class SegmentConfig {
@JsonProperty(value="txConfig", required = true)
@NotNull(message="Please provide a valid txConfig")
TelemetryConfig telemetryConfig;
@JsonProperty(value="rxConfig")
ExternalConfig externalConfig;
}
Upvotes: 2