Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change response JSON returned corresponding to @NotNull annotation

I have a simple code which return error json when customerId is not present in the RequestBody.

VO class:

public class OrderVO {

    private int orderId;
    @NotNull(message = "CustomerId Cant be null")
    private Long customerId;
}

Controller method:

@RequestMapping(value="/testOrderbyOrderid", method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
public void testOrderJson (@Valid @RequestBody OrderVO orderVO ) {

}

Currently when customerId is not present in the RequestBody, the structure of JSON returned is as shown below:

{
    "timestamp": "2019-05-14T17:08:01.318+0000",
    "status": 400,
    "error": "Bad Request",
    "errors": [
        {
            "codes": [   ],
            "arguments": [     ],
            "defaultMessage": "CustomerId Cant be null",
            "objectName": "orderVO",
            "field": "customerId",
            "rejectedValue": null,
            "bindingFailure": false,
            "code": "NotNull"
        }
    ],
    "message": "Validation failed for object='orderVO'. Error count: 1",
    "path": "/testOrderbyOrderid"
}

how can I change the above Json structure returned by @Notnull to JSON structure shown below :

{
    "timestamp": "2019-05-14T17:08:01.318+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "CustomerId Cant be null"
}

Edit - I already know that we can throw custom exception and handle it in ControllerAdvice, but consider if number of fields required for validation = 20, the amount of code required to check for null & throw exception would also scale up , making code look ugly. That is why I have posted this Qn.

like image 494
ASharma7 Avatar asked Jan 20 '26 03:01

ASharma7


2 Answers

Add methods below to your controller advice annotated exception handler:

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status,
            WebRequest request) {
        //return your custom error 
        //you can access to field errors using
        //ex.getBindingResult().getFieldErrors()
    }


    @ExceptionHandler(value = { javax.validation.ConstraintViolationException.class })
    protected ResponseEntity<Object> handleConstraintViolation(
            javax.validation.ConstraintViolationException ex) {
        //return your custom error message
    }

    @ExceptionHandler(value = { org.hibernate.exception.ConstraintViolationException.class })
    protected ResponseEntity<Object> handleHibernateConstraintViolation(
            org.hibernate.exception.ConstraintViolationException ex) {
        //return your custom error message
    }

like image 54
Ebrahim Pasbani Avatar answered Jan 22 '26 17:01

Ebrahim Pasbani


I guess we can also write Controller advice like this, without extending ResponseEntityExceptionHandler & overriding any of its method

@RestControllerAdvice
public class GlobalExceptionHandler {

        @ExceptionHandler(value = { MethodArgumentNotValidException.class })
        protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex){
        CustomException cex = new CustomException(ex.getBindingResult().getFieldError().getDefaultMessage());
        return new ResponseEntity<>(cex, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
like image 24
ASharma7 Avatar answered Jan 22 '26 15:01

ASharma7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!