@ notnull验证失败时返回响应代码为400

问题描述 投票:1回答:2

我正在使用javax和Hibernate实现来验证我的请求有效负载。

版本-org.hibernate:hibernate-validator:5.4.1.final

Sample Pojo:

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;

    public class Customer implements Serializable{

        @NotNull(message="name is null")
        @Size(min = 1)
        public String name;
    }

示例控制器:

    @RequestMapping(value = {"/customer"}, method = RequestMethod.POST)
    @ResponseBody
    public Customer doAdd(@RequestBody @Valid Customer inData){
        //some logic
return outData
    }

这里customer.name为null时,我得到的响应代码为422(不可处理的实体)。但是我想返回400(错误请求)。如何在此处覆盖响应代码?任何文件参考将不胜感激。

注意-我不想在控制器端进行这些验证,我可以在哪里检查并相应地发送响应代码。像这样-How to return 400 http status code with @NotNull?

java spring rest hibernate-validator
2个回答
0
投票

您应该在BindingResult之后立即设置Customer。喜欢:

@RequestMapping(value = {"/customer"}, method = RequestMethod.POST)
@ResponseBody
public Customer doAdd(@RequestBody @Valid Customer inData, BindingResult bindingResult){
    //some logic
    return outData
}

0
投票

您可以使用RestControllerAdvice相同

@RestControllerAdvice
public class ExceptionRestControllerAdvice {

    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public ExceptionResponseMessage handleInvalidParameterException(RuntimeException ex) {

        return sendResponse(HttpStatus.BAD_REQUEST, ex);
    }

    private ExceptionResponseMessage sendResponse(HttpStatus status, RuntimeException ex) {

        return new ExceptionResponseMessage(Instant.now(), status.value(), status.getReasonPhrase(),
                ex.getClass().toString(), ex.getMessage());
    }
}

public class ExceptionResponseMessage {

    private Instant time;
    private int status;
    private String error;
    private String exception;
    private String message;

    // setter and getter and constructor

© www.soinside.com 2019 - 2024. All rights reserved.