我必须使用Spring编写Rest Controller。
@PostMapping(value = "/mycontroller", produces = "application/json")
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public MyDTOOuptup myMethod(@Valid @RequestBody MyDTO input) {
... body ...
}
我编写了一个DTO输入对象,它表示控制器的请求主体。在DTO中,我添加了一些验证规则以在将请求分析到控制器之前验证输入。
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyDTO {
@NotNull(message="my custom error message for field_a")
@JsonProperty("field_A")
private String fieldA;
@NotNull(message="my custom error message for field_b")
@JsonProperty("field_B")
private String fieldB;
}
效果很好。如果输入错误,我会在响应正文中收到400-错误的请求和适当的错误描述。
但是,我看到这个json主体太冗长了。
{
"timestamp": "2020-03-31T14:29:42.401+0000",
"status": 400,
"error": "Bad Request",
"errors": [
{
"codes": [
"NotNull.myDTO.field_a",
"NotNull.field_a",
"NotNull.java.lang.String",
"NotNull"
],
"arguments": [
{
"codes": [
"myDTO.field_a",
"field_a"
],
"arguments": null,
"defaultMessage": "field_a",
"code": "field_a"
}
],
"defaultMessage": "my custom error message for field_a",
"objectName": "myDTO",
"field": "productId",
"rejectedValue": null,
"bindingFailure": false,
"code": "NotNull"
}
],
"message": "Validation failed for object='myDTO'. Error count: 1",
"path": "/mycontroller"
}
如何指定仅需要错误描述消息或类似内容?有没有精巧的结构?
您可以定义自己的自定义异常并添加异常处理程序,
class ExceptionResponse {
private boolean success = false;
private String errorCode;
private String errorMessage;
private String exception;
private List<String> errors;
private String path;
private String timestamp = LocalDateTime.now().toString();
}
异常处理程序,
@ControllerAdvice
public class CustomExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ExceptionResponse> invalidInput(MethodArgumentNotValidException ex, HttpServletRequest request) {
ExceptionResponse response = getExceptionResponse(); //generate exception response
return ResponseEntity.badRequest().contentType(MediaType.APPLICATION_JSON_UTF8).body(response);
}
}
希望对您有帮助!
这些属性在DefaultErrorAttributes
处作为DefaultErrorAttributes
可用。
Map<String, Object>
的默认实现。尽可能提供以下属性:...
如果要修改ErrorAttributes,则必须首先获取具有属性的地图,然后进行修改并最终将其返回。使用errors
方法获取属性。使用DefaultErrorAttributes::getErrorAttributes
从地图中删除非常简单。
这里是应该起作用的代码。返回的bean应该是DefaultErrorAttributes::getErrorAttributes
。
Map::remove