Arefe
Arefe

Reputation: 12417

Can @RequestBody pass null value inside?

I have a post method provide:

    @PostMapping("/products")
    public ResponseEntity<Object> newProduct(@RequestBody ProductDto newProduct) {
        try {
            if (newProduct == null) {
                return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.BAD_REQUEST,
                        MessageConstant.EMPTY_REQUEST_BODY_MSG), new HttpHeaders(), HttpStatus.BAD_REQUEST);
            }

            Product createProduct = productService.createProduct(newProduct);
            if (createProduct != null) {
                return new ResponseEntity<>(createProduct, new HttpHeaders(), HttpStatus.CREATED);
            } else {
                return new ResponseEntity<>(ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.UNPROCESSABLE_ENTITY,
                        MessageConstant.PRODUCT_CAN_NOT_CREATED_MSG), new HttpHeaders(), HttpStatus.UNPROCESSABLE_ENTITY);
            }

        } catch (Exception ex) {
            log.error(MessageConstant.INTERNAL_SERVER_ERROR_MSG + ex.getMessage());
            return new ResponseEntity<>(ApiResponseMessage.getInternalServerError(), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

I think this check is irrelevant and we don't need it. Because it's not possible to pass the null value inside the method.

if (newProduct == null) {
   return new ResponseEntity<> (ApiResponseMessage.getGenericApiResponse(Boolean.FALSE, HttpStatus.BAD_REQUEST,
                                MessageConstant.EMPTY_REQUEST_BODY_MSG), new HttpHeaders(), HttpStatus.BAD_REQUEST);
}

Is this correct?

Upvotes: 0

Views: 92

Answers (2)

prost&#253; člověk
prost&#253; člověk

Reputation: 939

If you are using just @RequestBody, then get below exception in client tool such as postman or other if you don't pass ProductDto, So checking NULL is not required.

{
    "timestamp": "2020-11-17T06:19:18.268+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "",
    "path": "/products"
}

Upvotes: 1

TroubleBoy
TroubleBoy

Reputation: 11

Maybe you can try @Valid, it might be better

Upvotes: 1

Related Questions