【问题标题】:How can I see the validation error returned from the rest api on kotlin?如何查看 kotlin 上其余 api 返回的验证错误?
【发布时间】:2021-04-11 04:46:30
【问题描述】:

我有一个基于 spring 的 rest api。检查我的 dto 类是否有错误

ErrorDetails.java

public class ErrorDetails {
public ErrorDetails(Date timestamp, String message, String details) {
    super();
    this.timestamp = timestamp;
    this.message = message;
    this.details = details;
}
public Date getTimestamp() {
    return timestamp;
}
public void setTimestamp(Date timestamp) {
    this.timestamp = timestamp;
}
public String getMessage() {
    return message;
}
public void setMessage(String message) {
    this.message = message;
}
public String getDetails() {
    return details;
}
public void setDetails(String details) {
    this.details = details;
}
private Date timestamp;
private String message;
private String details;


 }

GlobalExceptionHandler.java

@ControllerAdvice
public class GlobalExceptionHandler {


@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> customValidationErrorHanding(MethodArgumentNotValidException exception){
    ErrorDetails errorDetails = new ErrorDetails(new Date(), "Validation Error!",
            exception.getBindingResult().getFieldError().getDefaultMessage());
    return new ResponseEntity<>(errorDetails,HttpStatus.BAD_REQUEST);
}


}

CustomerDto.java

public class CustomerDto {

private String nickName;

@NotNull
@Size(min = 2 , max = 20 , message = "Incorret name")
private String name;

@NotNull
@Size(min = 2 , max = 20 , message = "Incorret surname")
private String surname;

@NotBlank
@Email
private String e_mail;

@NotNull
@Size(min = 6, max = 20, message = "Your password should be at least 6 character")
private String password;

@NotNull
private long balance;

@Nullable
private long carID;

  //getter and setter method...

 }

CustomerController.java

@RestController
public class CustomerController {


@Autowired
private CustomerService customerService;



@PostMapping("/addcustomer")
public Customer addCustomer(@Valid @RequestBody CustomerDto customer) {
    return customerService.save(customer);        
}
}

CustomerServiceImpl.java

@Transactional
@Service
public class CustomerServiceImpl implements CustomerService{

@Autowired
private CustomerRepository customerRepository;




@Override
public Customer save(CustomerDto customerdto){
    try {
        Customer customer = new Customer();
        convertToEntity(customer, customerdto);

        return customerRepository.save(customer);
    }
    
    catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    
    
}

CustomerRepository.java

@Repository
public interface CustomerRepository extends CrudRepository<Customer,String>{
}

比如我在postman app中测试,当客户密码小于6位时,我正确得到了错误。

{
"timestamp": "2021-01-04T20:32:40.665+00:00",
"message": "Validation Error!",
"details": "Your password should be at least 6 character"
}

我正在通过改造从 kotlin 连接到 spring。比如我发了一个密码小于6位的客户,怎么在kotlin中看到详细信息

这就是我在 kotlin 中发布客户帖子的方式

        val test= Customer("aaaa","aaaaa","aaaaaaa","aaaaaa@gmail.com","1",1111)

    val req= serviceNew.addCustomer(test)

    req.enqueue(object : Callback<String> {
        override fun onFailure(call: Call<String>, t: Throwable) {
            println(t.message)
            println("fail")
        }
        override fun onResponse(call: Call<String>, response: Response<String>) {
            if(response.isSuccessful) {
                println(response.body())
            }
            else
            {
                //println(????)
            }

        }

    })

【问题讨论】:

    标签: java android spring kotlin retrofit


    【解决方案1】:

    您可以使用response.message()response.code()response.errorBody() 方法获取响应消息或代码。这是改造响应的文档:https://square.github.io/retrofit/2.x/retrofit/retrofit2/Response.html

    在您的情况下,您可以使用 response.errorBody().string() 获取原始错误正文字符串,然后将此字符串转换为 JSONObject 并使用 .getString("details") 方法获取详细信息。

    【讨论】:

      猜你喜欢
      • 2012-09-07
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多