How do I catch NoSuchFileException from Util.readFileToString(), hiding behind a VertxException

429 views
Skip to first unread message

Kegan Holtzhausen

unread,
Feb 24, 2016, 6:51:05 AM2/24/16
to vert.x

Hi,

I have the following line of code:

String loc = adjustLocation(templateFileName);
String templateText = Utils.readFileToString(context.vertx(), loc);

And if my templateFile does not exist, I get the following stack:

INFO: Compiling Template: templates/blog2
io.vertx.core.VertxException: io.vertx.core.file.FileSystemException: java.nio.file.NoSuchFileException: templates/blog2.templ
at io.vertx.ext.web.impl.Utils.readFileToString(Utils.java:166)
at com.deblox.web.templ.impl.DxTemplateEngineImpl.getTemplate(DxTemplateEngineImpl.java:130)
at com.deblox.web.templ.impl.DxTemplateEngineImpl.render(DxTemplateEngineImpl.java:112)
at io.vertx.ext.web.handler.impl.TemplateHandlerImpl.handle(TemplateHandlerImpl.java:44)
at io.vertx.ext.web.handler.impl.TemplateHandlerImpl.handle(TemplateHandlerImpl.java:28)
at io.vertx.ext.web.impl.RouteImpl.handleContext(RouteImpl.java:221)



Now my problem comes from when I wrap the readFileToString in a try / catch, I am unable to catch anything except a VertxException. So how do I catch a NoSuchFileException? and deal with it accordingly?

      try {
        String templateText = Utils.readFileToString(context.vertx(), loc);
      } catch (NoSuchFileException e) {
        logger.error("No such template");
      }



/Kegan

Alexander Lehmann

unread,
Feb 24, 2016, 7:26:10 AM2/24/16
to vert.x
I think you have to catch VertxException and peek inside the exception with cause to get the actual exception.

try {
        String templateText = Utils.readFileToString(context.vertx(), loc);
      } catch (VertxException e) {
        if(e.cause instanceOf FileSystemException) {
          logger.error("No such template");
        } else {
          throw e;
        }
      }

or similar

Kegan Holtzhausen

unread,
Feb 25, 2016, 10:03:01 AM2/25/16
to vert.x
Thanks, I finally got it to work with nested getCause()'s. 

      try {
        templateText = Utils.readFileToString(context.vertx(), loc);
      } catch (VertxException e) {
        if (e.getCause().getCause() instanceof NoSuchFileException) {
          logger.error("No such template file " + loc);
          throw new NoSuchFileException("No such template file " + loc);
        } else {
          logger.error("Some other error " + e.getCause().getCause());
          throw e;
        }
      }



/K
Reply all
Reply to author
Forward
0 new messages