From 5d35892bc9f8c8b0a62c45a841d786a992b8b014 Mon Sep 17 00:00:00 2001 From: akshatdalton Date: Thu, 25 Mar 2021 14:05:19 +0000 Subject: [PATCH] linkifiers: Add helper function to handle API errors. This commit adds a helper function named `handle_linkifier_api_error` to `static/js/settings_linkifiers.js`. As the name suggests, this function handles the error returned from the API, specifically for operations on linkifiers (like adding linkifier). This is a prep commit for `Add setting to edit linkifiers`. Related issue: #10830. The main motive to add this helper function is to avoid copying substantial blocks of code, as it tends to result in someone later fixing bugs in only one of the two places. --- static/js/settings_linkifiers.js | 38 +++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/static/js/settings_linkifiers.js b/static/js/settings_linkifiers.js index ee3b4d1c76..838695b0aa 100644 --- a/static/js/settings_linkifiers.js +++ b/static/js/settings_linkifiers.js @@ -40,6 +40,25 @@ function sort_url(a, b) { return compare_values(a.url_format, b.url_format); } +function handle_linkifier_api_error(xhr, pattern_status, format_status, linkifier_status) { + // The endpoint uses the Django ValidationError system for error + // handling, which returns somewhat complicated error + // dictionaries. This logic parses them. + const errors = JSON.parse(xhr.responseText).errors; + if (errors.pattern !== undefined) { + xhr.responseText = JSON.stringify({msg: errors.pattern}); + ui_report.error($t_html({defaultMessage: "Failed"}), xhr, pattern_status); + } + if (errors.url_format_string !== undefined) { + xhr.responseText = JSON.stringify({msg: errors.url_format_string}); + ui_report.error($t_html({defaultMessage: "Failed"}), xhr, format_status); + } + if (errors.__all__ !== undefined) { + xhr.responseText = JSON.stringify({msg: errors.__all__}); + ui_report.error($t_html({defaultMessage: "Failed"}), xhr, linkifier_status); + } +} + export function populate_linkifiers(linkifiers_data) { if (!meta.loaded) { return; @@ -141,20 +160,13 @@ export function build_page() { ); }, error(xhr) { - const errors = JSON.parse(xhr.responseText).errors; add_linkifier_button.prop("disabled", false); - if (errors.pattern !== undefined) { - xhr.responseText = JSON.stringify({msg: errors.pattern}); - ui_report.error($t_html({defaultMessage: "Failed"}), xhr, pattern_status); - } - if (errors.url_format_string !== undefined) { - xhr.responseText = JSON.stringify({msg: errors.url_format_string}); - ui_report.error($t_html({defaultMessage: "Failed"}), xhr, format_status); - } - if (errors.__all__ !== undefined) { - xhr.responseText = JSON.stringify({msg: errors.__all__}); - ui_report.error($t_html({defaultMessage: "Failed"}), xhr, linkifier_status); - } + handle_linkifier_api_error( + xhr, + pattern_status, + format_status, + linkifier_status, + ); }, }); });