diff --git a/ghost/link-redirects/lib/LinkRedirectsService.js b/ghost/link-redirects/lib/LinkRedirectsService.js index b5bbc4f952..24e132dfde 100644 --- a/ghost/link-redirects/lib/LinkRedirectsService.js +++ b/ghost/link-redirects/lib/LinkRedirectsService.js @@ -85,34 +85,38 @@ class LinkRedirectsService { * @returns {Promise} */ async handleRequest(req, res, next) { - // skip handling if original url doesn't match the prefix - const fullURLWithRedirectPrefix = `${this.#baseURL.pathname}${this.#redirectURLPrefix}`; - // @NOTE: below is equivalent to doing: - // router.get('/r/'), (req, res) ... - // To make it cleaner we should rework it to: - // linkRedirects.service.handleRequest(router); - // and mount routes on top like for example sitemapHandler does - // Cleanup issue: https://github.com/TryGhost/Toolbox/issues/516 - if (!req.originalUrl.startsWith(fullURLWithRedirectPrefix)) { - return next(); + try { + // skip handling if original url doesn't match the prefix + const fullURLWithRedirectPrefix = `${this.#baseURL.pathname}${this.#redirectURLPrefix}`; + // @NOTE: below is equivalent to doing: + // router.get('/r/'), (req, res) ... + // To make it cleaner we should rework it to: + // linkRedirects.service.handleRequest(router); + // and mount routes on top like for example sitemapHandler does + // Cleanup issue: https://github.com/TryGhost/Toolbox/issues/516 + if (!req.originalUrl.startsWith(fullURLWithRedirectPrefix)) { + return next(); + } + + const url = new URL(req.originalUrl, this.#baseURL); + const link = await this.#linkRedirectRepository.getByURL(url); + + if (!link) { + return next(); + } + + const event = RedirectEvent.create({ + url, + link + }); + + DomainEvents.dispatch(event); + + res.setHeader('X-Robots-Tag', 'noindex, nofollow'); + return res.redirect(link.to.href); + } catch (e) { + return next(e); } - - const url = new URL(req.originalUrl, this.#baseURL); - const link = await this.#linkRedirectRepository.getByURL(url); - - if (!link) { - return next(); - } - - const event = RedirectEvent.create({ - url, - link - }); - - DomainEvents.dispatch(event); - - res.setHeader('X-Robots-Tag', 'noindex, nofollow'); - return res.redirect(link.to.href); } }