Skip to main content

relay_filter/
error_messages.rs

1//! Implements event filtering based on the error message
2//!
3//! Specific values in the error message or in the exception values can be used to
4//! filter messages with this filter.
5
6use std::borrow::Cow;
7
8use relay_pattern::{Gas, Patterns};
9
10use crate::{ErrorMessagesFilterConfig, FilterStatKey, Filterable};
11
12/// Checks events by patterns in their error messages.
13fn matches<F: Filterable>(item: &F, patterns: &Patterns) -> bool {
14    if let Some(logentry) = item.logentry() {
15        if let Some(message) = logentry.formatted.value() {
16            if patterns
17                .is_match(message.as_ref(), Gas::CONSTRAINED)
18                .unwrap_or(false)
19            {
20                return true;
21            }
22        } else if let Some(message) = logentry.message.value()
23            && patterns
24                .is_match(message.as_ref(), Gas::CONSTRAINED)
25                .unwrap_or(false)
26        {
27            return true;
28        }
29    }
30
31    if let Some(exception_values) = item.exceptions()
32        && let Some(exceptions) = exception_values.values.value()
33    {
34        for exception in exceptions {
35            if let Some(exception) = exception.value() {
36                let ty = exception.ty.as_str().unwrap_or_default();
37                let value = exception.value.as_str().unwrap_or_default();
38                let message = match (ty, value) {
39                    ("", value) => Cow::Borrowed(value),
40                    (ty, "") => Cow::Borrowed(ty),
41                    (ty, value) => Cow::Owned(format!("{ty}: {value}")),
42                };
43                if patterns
44                    .is_match(message.as_ref(), Gas::CONSTRAINED)
45                    .unwrap_or(false)
46                {
47                    return true;
48                }
49            }
50        }
51    }
52    false
53}
54
55/// Filters events by patterns in their error messages.
56pub fn should_filter<F: Filterable>(
57    item: &F,
58    config: &ErrorMessagesFilterConfig,
59) -> Result<(), FilterStatKey> {
60    if matches(item, &config.patterns) {
61        Err(FilterStatKey::ErrorMessage)
62    } else {
63        Ok(())
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use relay_event_schema::protocol::{Event, Exception, LogEntry, Values};
70    use relay_pattern::TypedPatterns;
71    use relay_protocol::Annotated;
72
73    use super::*;
74
75    #[test]
76    fn test_should_filter_exception() {
77        let configs = &[
78            // with globs
79            ErrorMessagesFilterConfig {
80                patterns: TypedPatterns::from([
81                    "filteredexception*".to_owned(),
82                    "*this is a filtered exception.".to_owned(),
83                    "".to_owned(),
84                    "this is".to_owned(),
85                ]),
86            },
87            // without globs
88            ErrorMessagesFilterConfig {
89                patterns: TypedPatterns::from([
90                    "filteredexception: this is a filtered exception.".to_owned(),
91                    "filteredexception".to_owned(),
92                    "this is a filtered exception.".to_owned(),
93                ]),
94            },
95        ];
96
97        let cases = &[
98            (
99                Some("UnfilteredException"),
100                None,
101                "UnfilteredException",
102                true,
103            ),
104            (
105                None,
106                Some("This is an unfiltered exception."),
107                "This is an unfiltered exception.",
108                true,
109            ),
110            (None, None, "This is an unfiltered exception.", true),
111            (None, None, "", true),
112            (
113                Some("UnfilteredException"),
114                Some("This is an unfiltered exception."),
115                "UnfilteredException: This is an unfiltered exception.",
116                true,
117            ),
118            (Some("FilteredException"), None, "FilteredException", false),
119            (
120                None,
121                Some("This is a filtered exception."),
122                "This is a filtered exception.",
123                false,
124            ),
125            (None, None, "This is a filtered exception.", false),
126            (
127                Some("FilteredException"),
128                Some("This is a filtered exception."),
129                "FilteredException: This is a filtered exception.",
130                false,
131            ),
132            (
133                Some("OtherException"),
134                Some("This is a random exception."),
135                "FilteredException: This is a filtered exception.",
136                false,
137            ),
138            (
139                None,
140                None,
141                "FilteredException: This is a filtered exception.",
142                false,
143            ),
144            (
145                Some("FilteredException"),
146                Some("This is a filtered exception."),
147                "hi this is a legit log message",
148                false,
149            ),
150        ];
151
152        for config in &configs[..] {
153            for &case in &cases[..] {
154                let (exc_type, exc_value, logentry_formatted, should_ingest) = case;
155                let event = Event {
156                    exceptions: Annotated::new(Values::new(vec![Annotated::new(Exception {
157                        ty: Annotated::from(exc_type.map(str::to_owned)),
158                        value: Annotated::from(exc_value.map(str::to_owned).map(From::from)),
159                        ..Default::default()
160                    })])),
161                    logentry: Annotated::new(LogEntry {
162                        formatted: Annotated::new(logentry_formatted.to_owned().into()),
163                        ..Default::default()
164                    }),
165                    ..Default::default()
166                };
167
168                assert_eq!(
169                    should_filter(&event, config),
170                    if should_ingest {
171                        Ok(())
172                    } else {
173                        Err(FilterStatKey::ErrorMessage)
174                    }
175                );
176            }
177        }
178    }
179
180    #[test]
181    fn test_filter_hydration_error() {
182        let pattern =
183            "*https://reactjs.org/docs/error-decoder.html?invariant={418,419,422,423,425}*";
184        let config = ErrorMessagesFilterConfig {
185            patterns: TypedPatterns::from([pattern.to_owned()]),
186        };
187
188        let event = Annotated::<Event>::from_json(
189            r#"{
190                "exception": {
191                    "values": [
192                        {
193                            "type": "Error",
194                            "value": "Minified React error #423; visit https://reactjs.org/docs/error-decoder.html?invariant=423 for the full message or use the non-minified dev environment for full errors and additional helpful warnings."
195                        }
196                    ]
197                }
198            }"#,
199        ).unwrap();
200
201        assert!(should_filter(&event.0.unwrap(), &config) == Err(FilterStatKey::ErrorMessage));
202    }
203
204    #[test]
205    fn test_filter_chunk_load_error_webpack() {
206        let errors = [
207            "Error: Uncaught (in promise): ChunkLoadError: Loading chunk 175 failed.",
208            "Uncaught (in promise): ChunkLoadError: Loading chunk 175 failed.",
209            "ChunkLoadError: Loading chunk 552 failed.",
210        ];
211
212        let config = ErrorMessagesFilterConfig {
213            patterns: TypedPatterns::from([
214                "ChunkLoadError: Loading chunk *".to_owned(),
215                "*Uncaught *: ChunkLoadError: Loading chunk *".to_owned(),
216            ]),
217        };
218
219        for error in errors {
220            let event = Event {
221                logentry: Annotated::new(LogEntry {
222                    formatted: Annotated::new(error.to_owned().into()),
223                    ..Default::default()
224                }),
225                ..Default::default()
226            };
227
228            assert_eq!(
229                should_filter(&event, &config),
230                Err(FilterStatKey::ErrorMessage)
231            );
232        }
233    }
234
235    #[test]
236    fn test_filter_chunk_load_error_turbopack() {
237        let errors = [
238            "Error: Uncaught (in promise): ChunkLoadError: Failed to load chunk 175.",
239            "Uncaught (in promise): ChunkLoadError: Failed to load chunk 175.",
240            "ChunkLoadError: Failed to load chunk 552.",
241        ];
242
243        let config = ErrorMessagesFilterConfig {
244            patterns: TypedPatterns::from([
245                "ChunkLoadError: Failed to load chunk *".to_owned(),
246                "*Uncaught *: ChunkLoadError: Failed to load chunk *".to_owned(),
247            ]),
248        };
249
250        for error in errors {
251            let event = Event {
252                logentry: Annotated::new(LogEntry {
253                    formatted: Annotated::new(error.to_owned().into()),
254                    ..Default::default()
255                }),
256                ..Default::default()
257            };
258
259            assert_eq!(
260                should_filter(&event, &config),
261                Err(FilterStatKey::ErrorMessage)
262            );
263        }
264
265        // Test exception-based matching for Turbopack
266        let exception_config = ErrorMessagesFilterConfig {
267            patterns: TypedPatterns::from(["ChunkLoadError: Failed to load chunk *".to_owned()]),
268        };
269
270        let exception_event = Event {
271            exceptions: Annotated::new(Values::new(vec![Annotated::new(Exception {
272                ty: Annotated::new("ChunkLoadError".to_owned()),
273                value: Annotated::new("Failed to load chunk 123.".to_owned().into()),
274                ..Default::default()
275            })])),
276            ..Default::default()
277        };
278
279        assert_eq!(
280            should_filter(&exception_event, &exception_config),
281            Err(FilterStatKey::ErrorMessage)
282        );
283    }
284}