spring boot validaciones


en la llamada agregar @valid

@PostMapping("/users")
public User addUser(@Valid @RequestBody User user) {
userService.save(user);
return user;
}

y en la clase user:

@NotBlank(message = "Please provide an email")
@Column(name="email")
private String email;

notBlank valida que el campo no sea nulo y que contenga al menos un caracter no blanco

la salida por default si se detectase el error seria asi

{
    "timestamp": "2020-03-29T22:13:23.653+0000",
    "status": 400,
    "error": "Bad Request",
    "errors": [
        {
            "codes": [
                "NotBlank.user.email",
                "NotBlank.email",
                "NotBlank.java.lang.String",
                "NotBlank"
            ],
            "arguments": [
                {
                    "codes": [
                        "user.email",
                        "email"
                    ],
                    "arguments": null,
                    "defaultMessage": "email",
                    "code": "email"
                }
            ],
            "defaultMessage": "Please provide an email",
            "objectName": "user",
            "field": "email",
            "rejectedValue": null,
            "bindingFailure": false,
            "code": "NotBlank"
        }
    ],
    "message": "Validation failed for object='user'. Error count: 1",

para hacer mas amigable esta salida
creamos la sigt clase:

package com.isra.Example3.error; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @ControllerAdvice public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { Map<String, Object> body = new LinkedHashMap<>(); body.put("timestamp", new Date()); body.put("status", status.value()); //Get all errors List<String> errors = ex.getBindingResult() .getFieldErrors() .stream() .map(x -> x.getDefaultMessage()) .collect(Collectors.toList()); body.put("errors", errors); return new ResponseEntity<>(body, headers, status); } }


y la salida sera

{
    "timestamp": "2020-03-29T22:29:58.799+0000",
    "status": 400,
    "errors": [
        "Please provide an email"
    ]
}


tambien podemos validar los parametros de entrada por ejemplo en un get

@Validated public class UserRestController {
...
public ResponseEntity<User> getUser(@Min(1) @PathVariable int id) {
../


y la salida seria

{
    "timestamp": "2020-03-29T23:10:02.890+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "getUser.id: tiene que ser mayor o igual que 1",
    "trace": "javax..........
}

ss
el codigo de error 500 (internal server) no es correcto vamos a override el metodo constraintViolationException de nuestra clase CustomGlobalExceptionHandler



No hay comentarios:

Publicar un comentario

linux ubuntu mint actualizar chrome

 desde una terminal: $ sudo apt update $ sudo apt install google-chrome-stable