Extend RepositoryRestExceptionHandler

 ̄綄美尐妖づ 提交于 2019-12-04 20:09:05

The RepositoryRestExceptionHandler is restricted to controllers from its own package - this basically means that it is just applied when the spring data rest controller (RepositoryEntityController) is invoked.

So I would just try to extend RepositoryRestExceptionHandler and annotate your subclass with a package that includes the controllers it should apply to :

@ControllerAdvice(basePackages="com.my.package")

This way you will not change the exception handling behaviour of spring data rest and make sure you just enhance the error handling of your controller methods.

I just tried this - so my custom controller (annotated with @RepositoryRestController) contains a method that throws a RepositoryConstraintViolationException. The spring data rest exception handler RepositoryRestExceptionHandler converts this exception into a BAD_REQUEST (400).

But this is not applied in my custom controller method - I get a INTERNAL_SERVER_ERROR (500).

So I extend the RepositoryRestExceptionHandler and annotate my controller advice so it only applies to the packages of my controller:

@ControllerAdvice(basePackageClasses = DefaultExceptionHandler.class)
public class DefaultExceptionHandler extends RepositoryRestExceptionHandler {

    @Autowired
    public DefaultExceptionHandler(MessageSource messageSource) {
        super(messageSource);
    }
}

With this ControllerAdvice in place I receive a BAD_REQUEST 400 - so this works as expected.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!