简体   繁体   中英

Custom spring boot validation response

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:

WARN 28840 --- [nio-8080-exec-1].wsmsDefaultHandlerExceptionResolver: Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public org.springframework.http.ResponseEntity

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

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

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
// omitted input

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM