Spring数据休息验证+异常映射器:令人困惑 [英] Spring data rest validation + exception mapper: confusing

查看:173
本文介绍了Spring数据休息验证+异常映射器:令人困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Data Rest,一切顺利。

I am using Spring Data Rest and all is going well.

我想在我的实体上应用验证(JSR 303)。

I want to apply validation (JSR 303) on my entities.

Spring文档说我可以通过几种方式拦截应用程序事件(我无法开始工作,而现在spring.io似乎已经失效)。

The spring docs say I can intercept application events in a few ways (none of which I can get to work, and right now spring.io seems to be down).

然而,我确实通过投入

@Validated

@Validated

在我的存储库中:

@Validated
@RepositoryRestResource(collectionResourceRel = "workers", path = "workers")
public interface WorkerRepository extends PagingAndSortingRepository<Worker, Long> {

}

它会引发异常。问题是它是一个弹簧异常,甚至不是根目录,我需要基本上进行验证并将它们转换为自定义实体有效负载:

And it will throw an exception. Problem is it's a spring exception and not even the root one, and I need to basically take the validations and turn them into a custom entity payload of:

{
  "foo": "must be of length 10",
  "baz": "Must match pattern '[A-Z]+'"
}

所以,简而言之,我想


  • 使用JSR 303验证实体

  • 使用400生成HTTP实体:和映射或字段 - >错误

最简单的方法是什么?
我也偶然发现了这个:

What's the most straightforward way to do this? I also stumbled on this:

Detected @ExceptionHandler methods in repositoryRestExceptionHandler

这看起来很有用。当我查看该类时,它看起来像我需要的肯定

Which seems suspiciously useful. When I checkout that class it looks like what I need for sure

推荐答案

Spring数据休息不会自动应用bean验证。如果你想要bean验证,你需要在spring数据休息中注册相应的验证器。

Spring data rest is not applying bean validation automatically. If you want bean validation you need to register the appropriate validator in spring data rest.

以下配置对我有用:

@Configuration
public class MyValidationConfiguration extends RepositoryRestConfigurerAdapter {

    @Bean
    @Primary
    /**
     * Create a validator to use in bean validation - primary to be able to autowire without qualifier
     */
    Validator validator() {
        return new LocalValidatorFactoryBean();
    }

    @Override
    public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
        Validator validator = validator();
        //bean validation always before save and create
        validatingListener.addValidator("beforeCreate", validator);
        validatingListener.addValidator("beforeSave", validator);
    }
} 

使用此配置,每个具有bean验证约束的实体都是在更新和创建之前验证。

With this configuration every entity that has bean validation constraints is validated before update and create.

(这不是在spring-data-rest项目中为自定义控制器启用bean验证 - 但这不是你要求的 - 是吗?)

(This is not enabling bean validation for custom controllers in a spring-data-rest project - but this is not what your are asking for - is it?)


  • 弹簧数据休息验证机制抛出 RepositoryConstraintViolationException

  • RepositoryRestExceptionHandler

  • 处理,导致错误被序列化为 RepositoryConstraintViolationExceptionMessage

  • the spring data rest validation mechanism is throwing a RepositoryConstraintViolationException
  • which is handled by RepositoryRestExceptionHandler
  • which results in the errors being serialized as RepositoryConstraintViolationExceptionMessage

因此验证错误响应将导致 400错误的请求有这样的正文:

So a validation error response would result in a 400 Bad Request with a body like this:

{
  "errors" : [ {
    "entity" : "MyEntity",
    "message" : "may not be null",
    "invalidValue" : "null",
    "property" : "price"
  }, {
    "entity" : "MyEntity",
    "message" : "may not be empty",
    "invalidValue" : "",
    "property" : "name"
  }
}

自定义控制器

您可以使用spring-data-rest实体生命周期来利用spring-data-rest注册的验证器应用程序事件。例如你可以发出 BeforeSaveEvent 将触发所有事件处理程序以及spring-data-rest提供的验证事件侦听器。因此,您可以实现获得相同的错误和错误表示。

You can leverage your spring-data-rest registered validators using the spring-data-rest entity lifecycle application events. e.g. you can emit a BeforeSaveEvent in your custom controller to trigger all your event handlers and also the validating event listener that spring-data-rest provides. Thus you can achieve to get the same errors and error representation.

这篇关于Spring数据休息验证+异常映射器:令人困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆