From f7b853373cd1f13c42d4978196bbd3ef6bd6fdfe Mon Sep 17 00:00:00 2001 From: Veloman Yunkan Date: Sat, 11 Dec 2021 20:54:16 +0400 Subject: [PATCH] Less confusing 404 errors from /random endpoint Before this fix the /random endpoint could return a 404 Not Found page saying The requested URL "/random" was not found on this server. Error cases producing such a result were: - `/random?content=NON-EXISTING-BOOK` (can happen when a server is restarted or the library is reloaded and the current book is no longer available). - Failure of the libkiwix routine for picking a random article. Now a proper message is shown for each of those cases. --- src/server/internalServer.cpp | 8 +++++--- src/server/response.cpp | 4 +++- static/templates/404.html | 2 ++ 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/server/internalServer.cpp b/src/server/internalServer.cpp index 6ff949380..11333f30c 100644 --- a/src/server/internalServer.cpp +++ b/src/server/internalServer.cpp @@ -668,18 +668,20 @@ std::unique_ptr InternalServer::handle_random(const RequestContext& re bookId = mp_nameMapper->getIdForName(bookName); archive = mp_library->getArchiveById(bookId); } catch (const std::out_of_range&) { - return Response::build_404(*this, request, bookName, ""); + // error handled by the archive == nullptr check below } if (archive == nullptr) { - return Response::build_404(*this, request, bookName, ""); + const std::string error_details = "No such book: " + bookName; + return Response::build_404(*this, request, bookName, "", error_details); } try { auto entry = archive->getRandomEntry(); return build_redirect(bookName, getFinalItem(*archive, entry)); } catch(zim::EntryNotFound& e) { - return Response::build_404(*this, request, bookName, ""); + const std::string error_details = "Oops! Failed to pick a random article :("; + return Response::build_404(*this, request, bookName, getArchiveTitle(*archive), error_details); } } diff --git a/src/server/response.cpp b/src/server/response.cpp index 69408f0de..9fefd5f88 100644 --- a/src/server/response.cpp +++ b/src/server/response.cpp @@ -86,7 +86,9 @@ std::unique_ptr Response::build_304(const InternalServer& server, cons std::unique_ptr Response::build_404(const InternalServer& server, const RequestContext& request, const std::string& bookName, const std::string& bookTitle, const std::string& details) { MustacheData results; - results.set("url", request.get_full_url()); + if ( request.get_url() != "/random" ) { + results.set("url", request.get_full_url()); + } results.set("details", details); auto response = ContentResponse::build(server, RESOURCE::templates::_404_html, results, "text/html"); diff --git a/static/templates/404.html b/static/templates/404.html index 501c6ebb3..55645dbd7 100644 --- a/static/templates/404.html +++ b/static/templates/404.html @@ -6,9 +6,11 @@

Not Found

+ {{#url}}

The requested URL "{{url}}" was not found on this server.

+ {{/url}} {{#details}}

{{{details}}}