New to Spring, so I want to return either a 400 or a 201 (Created) with a REST endpoint, but right now it only returns an empty 200 response via Postman.
SampleService.java
@Service
public class SampleService {
private SampleRepository sampleRepository;
@Autowired
public SampleService(SampleRepository sampleRepository) {
this.sampleRepository = sampleRepository;
}
public ResponseEntity<Response> registerData(Data data) {
Optional<SampleData> dataOptional = sampleRepository.findDataByName(data.getName());
if(dataOptional.isPresent()) {
// Returns blank 200 response
return new ResponseEntity<>(
new Error(
"Bad Request",
"Data already exists."
),
HttpStatus.BAD_REQUEST
);
}
sampleRepository.save(data);
// Returns blank 200 response
return ResponseEntity.status(HttpStatus.CREATED)
.body(
// I haven't got far to creating a response, so do not mind the "Error".
new Error("Created", "Stand-in until created proper response")
);
}
}
Response.java
public interface Response {}
Error.java
public class Error implements Response {
private String errorType;
private String errorMessage;
public Error(String errorType, String errorMessage) {
this.errorType = errorType;
this.errorMessage = errorMessage;
}
public String getErrorType() {
return errorType;
}
public void setErrorType(String errorType) {
this.errorType = errorType;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
If anyone needs anything else, let me know, but this should be enough to cover.
question from:
https://stackoverflow.com/questions/65844701/spring-responseentity-not-being-used 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…