我正在尝试将控制器处理程序方法上的某些验证注释中提供的消息添加到请求的响应中。
例如,
message
注释上的@Pattern
属性:
@RestController
@RequestMapping("/api")
public class Controller {
@GetMapping
private ResponseEntity<String> get(@Valid @RequestParam(name = "param")
@Pattern(regexp = "^[a-zA-Z0-9]{6}$",
message = "The request parameter must be 6 characters long and consist of alphanumeric characters.")
String param) {
return ResponseEntity.ok().build();
}
}
如果出现验证错误,我希望得到
problem detail
形式的响应。 (参见spring文档和RFC-7807)。
在这个例子中看起来像:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "The request parameter must be 6 characters long and consist of alphanumeric characters.",
"instance": "/api"
}
注意:您可以通过扩展
@ControllerAdvice
类来启用此类输出 ResponseEntityExceptionHandler
但是,本例中的标准输出是:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Validation failure",
"instance": "/api"
}
'Validation failure'
是 'HandlerMethodValidationException'
的构造函数中存在的硬编码消息,这是响应验证错误而引发的异常。
一种解决方案是提供所需的消息以及消息代码:
problemDetail.org.springframework.web.method.annotation.HandlerMethodValidationException
这可行,但限制您的消息非常笼统。因为抛出相同异常的另一个验证错误将与相同的消息有关。 它还违背了注释上这些消息属性的目的。
通过查看代码,我最初的猜测是 Spring 框架目前尚不支持此功能。但也许其他人有更好的主意。
Spring启动版本:3.2.2
春季版本:6.1.3
您需要创建一个用 @ControllerAdvice 注释的类,创建一个类似于下面示例的方法
@ExceptionHandler(value = HandlerMethodValidationException.class)
public ResponseEntity<ErrorMessage> handleTenantException(HandlerMethodValidationExceptionex) {
// here you get your message and return your custom error object (im my example ErrorMessage class)
return ResponseEntity.badRequest().body(errorMessage);
}