Repository navigation
Expand file tree
/
Copy pathbuildSlackJobFailureMessage.m
More file actions
80 lines (68 loc) · 2.28 KB
/
Copy pathbuildSlackJobFailureMessage.m
File metadata and controls
80 lines (68 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
function msg = buildSlackJobFailureMessage(action, context, err)
%BUILDSLACKJOBFAILUREMESSAGE Build the Slack text reporting a failed job upload
%
% Produces
%
% :rotating_light: RecordingProcessJobGUI: <action> failed
% • <field>: <value>
% ...
% Error: <message>
%
% Kept free of the DB and the network so it can be tested on its own;
% notifySlackJobFailure does the sending.
%
% Inputs:
% action (char/string) - What was being done, e.g. 'Job creation'
% context (struct or [])- Fields listed in order, e.g. system, job_id.
% Numbers, logicals, strings and one-element
% cells are formatted; empty values read
% '(none)', so a job_id of 0 still shows.
% err (MException/char/string) - The failure; '' reads '(no message)'
%
% Outputs:
% msg (char) - The text, with Slack's control characters (& < >)
% escaped so an error or path can't ping or link anything
%
% See also: notifySlackJobFailure
lines = {sprintf(':rotating_light: RecordingProcessJobGUI: %s failed', ...
escapeSlack(char(action)))};
if isstruct(context) && isscalar(context)
fields = fieldnames(context);
for i = 1:numel(fields)
lines{end+1} = sprintf('%s %s: %s', char(8226), fields{i}, ...
escapeSlack(formatValue(context.(fields{i})))); %#ok<AGROW>
end
end
if isa(err, 'MException')
err_msg = err.message;
else
err_msg = char(err);
end
if isempty(strtrim(err_msg))
err_msg = '(no message)';
end
lines{end+1} = ['Error: ' escapeSlack(err_msg)];
msg = strjoin(lines, newline);
end
function txt = formatValue(value)
if iscell(value) && isscalar(value)
value = value{1};
end
if isempty(value)
txt = '(none)';
elseif ischar(value) || isstring(value)
txt = char(strjoin(string(value), ', '));
elseif islogical(value)
txt = strjoin(cellstr(string(value)), ', ');
elseif isnumeric(value)
txt = strjoin(arrayfun(@num2str, value(:)', 'UniformOutput', false), ', ');
else
txt = ['<' class(value) '>'];
end
end
function txt = escapeSlack(txt)
% & first, so the entities added for < and > are not escaped again.
txt = strrep(txt, '&', '&');
txt = strrep(txt, '<', '<');
txt = strrep(txt, '>', '>');
end