如果必需的属性具有空值或空值,如何抛出异常?
How to throw an exception if required properties have either null or empty values?
我想在将接收到的对象解析为 DTO 时抛出异常,并且在解析 DTO 中标记为必需的任何字段是否具有空值时,我想抛出 400 响应的异常。
我有一个这样的控制器,
public class StandardController(@RequestBody Object body) {
ModelMapper modelMapper = new ModelMapper();
try {
CustomDTO customDto = modelMapper.map(body, CustomDTO.class);
} catch (Exception e) {
//throw exception with a message required properties are missing with 400 response`
}
}
我在我的 CustomDTO 中将一些属性标记为 required = true
和 JsonProperty
。但是当我测试控制器时,它没有抛出异常。
知道如何实现这个场景吗?
在Spring启动控制器中,您可以使用ResponseStatusException。
这样的事情应该有效:
try {
//Your Code here
} catch(Exception e) {
throw new ResponseStatusException( HttpStatus.BAD_REQUEST, "Required properties are missing");
}
此外,如果您想了解有关这种异常处理方式的更多信息,可以在 Baeldung 上查看 this article。
您需要直接从用户那里接收 CustomDto。因为DTO是用来传输的。如果您收到来自用户的自定义 dto,那么您可以在对象上添加验证。
举个例子
@Data
public class ClassDto {
private Long classId;
@NotNull
@Size(max = 200)
private String className;
private Double classAdmissionFee;
}
查看@NotNull 和@Size 注释。他们接受 javax 验证。
现在在您的 DTO 完全配置后一次。您需要这样做:
public class StandardController(@Valid @RequestBody CustomDTO customDto) {
}
注意@Valid 注释。当任何 DTO 约束失败时 spring 将抛出 MethodArgumentNotValidException。所以你需要通过@ControllerAdvice 或扩展ResponseEntityExceptionHandler 来处理异常。
这里有一篇很好的文章 link 适合您的案例:
https://www.javaguides.net/2021/04/spring-boot-dto-validation-example.html
我想在将接收到的对象解析为 DTO 时抛出异常,并且在解析 DTO 中标记为必需的任何字段是否具有空值时,我想抛出 400 响应的异常。
我有一个这样的控制器,
public class StandardController(@RequestBody Object body) {
ModelMapper modelMapper = new ModelMapper();
try {
CustomDTO customDto = modelMapper.map(body, CustomDTO.class);
} catch (Exception e) {
//throw exception with a message required properties are missing with 400 response`
}
}
我在我的 CustomDTO 中将一些属性标记为 required = true
和 JsonProperty
。但是当我测试控制器时,它没有抛出异常。
知道如何实现这个场景吗?
在Spring启动控制器中,您可以使用ResponseStatusException。 这样的事情应该有效:
try {
//Your Code here
} catch(Exception e) {
throw new ResponseStatusException( HttpStatus.BAD_REQUEST, "Required properties are missing");
}
此外,如果您想了解有关这种异常处理方式的更多信息,可以在 Baeldung 上查看 this article。
您需要直接从用户那里接收 CustomDto。因为DTO是用来传输的。如果您收到来自用户的自定义 dto,那么您可以在对象上添加验证。
举个例子
@Data
public class ClassDto {
private Long classId;
@NotNull
@Size(max = 200)
private String className;
private Double classAdmissionFee;
}
查看@NotNull 和@Size 注释。他们接受 javax 验证。
现在在您的 DTO 完全配置后一次。您需要这样做:
public class StandardController(@Valid @RequestBody CustomDTO customDto) {
}
注意@Valid 注释。当任何 DTO 约束失败时 spring 将抛出 MethodArgumentNotValidException。所以你需要通过@ControllerAdvice 或扩展ResponseEntityExceptionHandler 来处理异常。
这里有一篇很好的文章 link 适合您的案例: https://www.javaguides.net/2021/04/spring-boot-dto-validation-example.html