Home > Blockchain >  Custom spring boot validation response
Custom spring boot validation response

Time:12-06

I used spring-boot validation below:

in gradle:

implementation 'org.springframework.boot:spring-boot-starter-validation'

in request:

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class ApiTransactionRequest {
    private String id;
    @NotNull
    private String transaction_id;
    @NotNull
    private String apiOperation;
    @NotNull
...

When testing this case I got these infos: Spring app show this log: enter image description here

Http Response(spring boot validation response message)

{
   "timestamp": "2022-12-05T09:58:55.011 00:00",
   "status": 400,
   "error": "Bad Request",
   "path": "/transactions"
}

Actually I want to get the custom http response instead spring boot validation message, like this:

{
   "date": "2022-12-05",
   "status": 400.03,
   "error": "Transaction id is invalid",
   "message": "Transaction id is not null"
}

Any helps, tks

CodePudding user response:

You need to use @ControllerAdvice and make a custom exception handling. Spring should thrown MethodArgumentNotValidException or ConstraintViolationException - it depends do you throw the exception from the Controller or not.

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<MyResponse> handleException(MethodArgumentNotValidException exception) {
        String customException = exception.getBindingResult().getFieldErrors().stream()
                       .map(x -> x.getField()   x.getDefaultMessage())
                       .collect(Collectors.joining(","))

        return  ResponseEntity.badRequest().body(new MyResponse(customException);
    }

MyResponse could have the message

CodePudding user response:

Hey if you want a normal API Jason Request please use @Entity instead:

@Entity

public class ApiTransactionRequest { @Id @GeneratedValue(strategy = GenerationType.AUTO) //Add this line if you your ID will be created by the Webapp @NotNull private String id; @NotNull private String transaction_id; @NotNull private String apiOperation; @NotNull ...

In your Controller you will to Something like this

@RestController

public class UserController {

@PostMapping("/users")
ResponseEntity<String> addUser(@Valid @RequestBody User user) {
    // persisting the user
    return ResponseEntity.ok("User is valid");
}

// standard constructors / other methods

}

you can look it up here: https://www.baeldung.com/spring-boot-bean-validation

  • Related