[Sling Model] Is there a way to use adaptTo and catch any thrown exceptions? | Community
Skip to main content
Level 2
Oct 22, 2019 11:13 PM UTC
Solved

[Sling Model] Is there a way to use adaptTo and catch any thrown exceptions?

We have been making decent use of sling models on our site, but one of the things that has been frustrating is that whenever an exception is thrown as part of the adaptTo step it seems to get eaten in the process, leaving behind a null object.  Is there a way to do an adaptTo step and actually catch any exceptions?

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
ElkishAccepted solution
Level 2
Oct 23, 2019 4:48 PM UTC

So I actually found the solution while looking through docs on an unrelated issue:

Apache Sling :: Sling Models

It looks like Sling has a factory class you can use that will pass exceptions when used to adapt objects to new types.  Instead of using the object's adaptTo function, you can simply use:

MyModel model = modelFactory.createModel(object, MyModel.class);

Which will throw catchable exceptions.

2 replies

joerghoh
Employee
Oct 27, 2019 2:39 PM UTC

Good to know that you have a found a way to deal with that; but in general adaptTo() does not allow exceptions to be thrown. I remeber a discussion on the sling list of this behavior should be changed, but I do not recall why this proposal has been declined.

Anyway, I find this behavior also odd, unless you start using it in combination with Java8's Optional type.

Translate
ElkishAuthorAccepted solution
Level 2
Oct 23, 2019 4:48 PM UTC

So I actually found the solution while looking through docs on an unrelated issue:

Apache Sling :: Sling Models

It looks like Sling has a factory class you can use that will pass exceptions when used to adapt objects to new types.  Instead of using the object's adaptTo function, you can simply use:

MyModel model = modelFactory.createModel(object, MyModel.class);

Which will throw catchable exceptions.

Translate