0
# Error Handling and Debugging
1
2
Error handling patterns, debugging utilities, and troubleshooting for image loading issues in Glide applications.
3
4
## Capabilities
5
6
### Request Listeners
7
8
Event listeners for monitoring request success, failure, and lifecycle events.
9
10
```java { .api }
11
/**
12
* Request event listener interface
13
*/
14
public interface RequestListener<R> {
15
/**
16
* Called when request fails
17
* @param e Exception details
18
* @param model Source model that failed
19
* @param target Target for the request
20
* @param isFirstResource true if this is the first resource requested
21
* @return true to prevent default error handling
22
*/
23
boolean onLoadFailed(@Nullable GlideException e, Object model, Target<R> target, boolean isFirstResource);
24
25
/**
26
* Called when resource is ready
27
* @param resource Loaded resource
28
* @param model Source model
29
* @param target Target for the request
30
* @param dataSource Where resource was loaded from
31
* @param isFirstResource true if this is the first resource loaded
32
* @return true to prevent default resource handling
33
*/
34
boolean onResourceReady(R resource, Object model, Target<R> target, DataSource dataSource, boolean isFirstResource);
35
}
36
37
/**
38
* Experimental request listener with additional callbacks
39
*/
40
public interface ExperimentalRequestListener<R> extends RequestListener<R> {
41
/**
42
* Called when request starts
43
* @param model Source model
44
* @param target Request target
45
* @return true to prevent default start handling
46
*/
47
boolean onLoadStarted(@Nullable Object model, Target<R> target);
48
49
/**
50
* Called when request is cleared
51
* @param model Source model
52
* @param target Request target
53
* @return true to prevent default clear handling
54
*/
55
boolean onLoadCleared(@Nullable Object model, Target<R> target);
56
}
57
```
58
59
**Usage Examples:**
60
61
```java
62
// Basic request listener
63
RequestListener<Drawable> listener = new RequestListener<Drawable>() {
64
@Override
65
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
66
Log.e("Glide", "Failed to load image: " + model, e);
67
// Return false to allow default error handling (show error drawable)
68
return false;
69
}
70
71
@Override
72
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
73
Log.d("Glide", "Image loaded from: " + dataSource.name());
74
// Return false to allow default resource handling (display image)
75
return false;
76
}
77
};
78
79
Glide.with(context)
80
.load(imageUrl)
81
.listener(listener)
82
.into(imageView);
83
84
// Multiple listeners
85
Glide.with(context)
86
.load(imageUrl)
87
.listener(analyticsListener)
88
.addListener(debugListener)
89
.addListener(performanceListener)
90
.into(imageView);
91
```
92
93
### Glide Exceptions
94
95
Exception hierarchy and error information for troubleshooting failed requests.
96
97
```java { .api }
98
/**
99
* Main exception class for Glide errors
100
*/
101
public final class GlideException extends Exception {
102
/**
103
* Get the root cause of the exception
104
* @return Root cause throwable
105
*/
106
@Nullable public Throwable getCause();
107
108
/**
109
* Get all root causes in the exception chain
110
* @return List of root cause throwables
111
*/
112
@NonNull public List<Throwable> getRootCauses();
113
114
/**
115
* Log all root causes with specified tag
116
* @param tag Log tag to use
117
*/
118
public void logRootCauses(@NonNull String tag);
119
120
/**
121
* Get detailed error message with causes
122
* @return Formatted error message
123
*/
124
@Override
125
public String getMessage();
126
127
/**
128
* Get the exception class that caused the failure
129
* @return Exception class
130
*/
131
@NonNull public Class<?> getOrigin();
132
133
/**
134
* Get data source that failed
135
* @return Data source enum
136
*/
137
@NonNull public DataSource getDataSource();
138
}
139
```
140
141
**Error Handling Examples:**
142
143
```java
144
Glide.with(context)
145
.load(imageUrl)
146
.listener(new RequestListener<Drawable>() {
147
@Override
148
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
149
if (e != null) {
150
// Log detailed error information
151
Log.e("ImageLoad", "Failed to load: " + model);
152
e.logRootCauses("ImageLoad");
153
154
// Check specific error types
155
List<Throwable> causes = e.getRootCauses();
156
for (Throwable cause : causes) {
157
if (cause instanceof UnknownHostException) {
158
showNetworkError();
159
} else if (cause instanceof FileNotFoundException) {
160
showFileNotFoundError();
161
} else if (cause instanceof OutOfMemoryError) {
162
showMemoryError();
163
}
164
}
165
}
166
return false;
167
}
168
169
@Override
170
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
171
return false;
172
}
173
})
174
.into(imageView);
175
```
176
177
### Data Source Information
178
179
Information about where resources were loaded from for debugging and analytics.
180
181
```java { .api }
182
/**
183
* Data source enumeration
184
*/
185
public enum DataSource {
186
/** Loaded from local file system */
187
LOCAL,
188
189
/** Loaded from remote URL */
190
REMOTE,
191
192
/** Loaded from disk cache (original data) */
193
DATA_DISK_CACHE,
194
195
/** Loaded from disk cache (transformed resource) */
196
RESOURCE_DISK_CACHE,
197
198
/** Loaded from memory cache */
199
MEMORY_CACHE
200
}
201
```
202
203
**Data Source Usage:**
204
205
```java
206
RequestListener<Drawable> analyticsListener = new RequestListener<Drawable>() {
207
@Override
208
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
209
// Track performance metrics
210
switch (dataSource) {
211
case MEMORY_CACHE:
212
analytics.trackImageCacheHit("memory");
213
break;
214
case DATA_DISK_CACHE:
215
case RESOURCE_DISK_CACHE:
216
analytics.trackImageCacheHit("disk");
217
break;
218
case REMOTE:
219
analytics.trackImageNetworkLoad();
220
break;
221
case LOCAL:
222
analytics.trackImageLocalLoad();
223
break;
224
}
225
return false;
226
}
227
228
@Override
229
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
230
analytics.trackImageLoadError(model.toString(), e);
231
return false;
232
}
233
};
234
```
235
236
### Debugging Utilities
237
238
Tools and utilities for debugging image loading issues.
239
240
```java { .api }
241
/**
242
* Debugging and tracing utilities
243
*/
244
public final class GlideTrace {
245
/**
246
* Begin tracing section for performance analysis
247
* @param name Section name
248
*/
249
public static void beginSection(@NonNull String name);
250
251
/**
252
* End current tracing section
253
*/
254
public static void endSection();
255
256
/**
257
* Begin section with formatted name
258
* @param format Format string
259
* @param args Format arguments
260
*/
261
public static void beginSectionFormat(@NonNull String format, Object... args);
262
}
263
264
/**
265
* Logging utilities
266
*/
267
public final class LogLevel {
268
public static final int VERBOSE = 2;
269
public static final int DEBUG = 3;
270
public static final int INFO = 4;
271
public static final int WARN = 5;
272
public static final int ERROR = 6;
273
}
274
```
275
276
**Debugging Examples:**
277
278
```java
279
// Enable verbose logging in module
280
@Override
281
public void applyOptions(Context context, GlideBuilder builder) {
282
builder.setLogLevel(Log.VERBOSE)
283
.setLogRequestOrigins(true);
284
}
285
286
// Performance tracing
287
public class TracingRequestListener implements RequestListener<Drawable> {
288
@Override
289
public boolean onLoadStarted(@Nullable Object model, Target<Drawable> target) {
290
GlideTrace.beginSection("ImageLoad: " + model);
291
return false;
292
}
293
294
@Override
295
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
296
GlideTrace.endSection();
297
return false;
298
}
299
300
@Override
301
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
302
GlideTrace.endSection();
303
return false;
304
}
305
}
306
```
307
308
### Common Error Patterns
309
310
Typical error scenarios and their solutions.
311
312
```java { .api }
313
/**
314
* Common error handling patterns
315
*/
316
public class ErrorHandlingPatterns {
317
/**
318
* Handle network connectivity issues
319
*/
320
public static void handleNetworkErrors(GlideException e, String fallbackUrl) {
321
List<Throwable> causes = e.getRootCauses();
322
for (Throwable cause : causes) {
323
if (cause instanceof UnknownHostException ||
324
cause instanceof ConnectException ||
325
cause instanceof SocketTimeoutException) {
326
// Retry with fallback or show offline indicator
327
loadFallbackImage(fallbackUrl);
328
break;
329
}
330
}
331
}
332
333
/**
334
* Handle memory pressure
335
*/
336
public static void handleMemoryErrors(Context context, GlideException e) {
337
for (Throwable cause : e.getRootCauses()) {
338
if (cause instanceof OutOfMemoryError) {
339
// Clear memory cache and retry
340
Glide.get(context).clearMemory();
341
// Reduce image quality for subsequent loads
342
RequestOptions options = new RequestOptions()
343
.format(DecodeFormat.PREFER_RGB_565)
344
.downsample(DownsampleStrategy.AT_MOST);
345
break;
346
}
347
}
348
}
349
350
/**
351
* Handle invalid URLs or missing resources
352
*/
353
public static boolean handleMissingResource(GlideException e, Object model) {
354
for (Throwable cause : e.getRootCauses()) {
355
if (cause instanceof FileNotFoundException ||
356
cause instanceof MalformedURLException) {
357
Log.w("Glide", "Invalid resource: " + model);
358
return true; // Resource is invalid
359
}
360
}
361
return false;
362
}
363
}
364
```
365
366
**Error Pattern Usage:**
367
368
```java
369
RequestListener<Drawable> robustListener = new RequestListener<Drawable>() {
370
@Override
371
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
372
if (e != null) {
373
// Handle network issues
374
if (isNetworkError(e)) {
375
ErrorHandlingPatterns.handleNetworkErrors(e, fallbackImageUrl);
376
return true; // Prevent default error drawable
377
}
378
379
// Handle memory issues
380
if (isMemoryError(e)) {
381
ErrorHandlingPatterns.handleMemoryErrors(context, e);
382
// Retry with lower quality
383
retryWithLowerQuality(model, target);
384
return true;
385
}
386
387
// Handle invalid resources
388
if (ErrorHandlingPatterns.handleMissingResource(e, model)) {
389
showPlaceholder(target);
390
return true;
391
}
392
}
393
return false;
394
}
395
396
@Override
397
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
398
return false;
399
}
400
};
401
```
402
403
## Types
404
405
```java { .api }
406
// Exception cause information
407
public static class Cause {
408
@NonNull private final Throwable exception;
409
@NonNull private final String description;
410
411
public Cause(@NonNull Throwable exception, @NonNull String description);
412
@NonNull public Throwable getException();
413
@NonNull public String getDescription();
414
}
415
416
// Request origin tracking
417
public static class RequestOrigin {
418
@NonNull private final String stackTrace;
419
@NonNull private final String threadName;
420
421
public RequestOrigin(@NonNull String stackTrace, @NonNull String threadName);
422
@NonNull public String getStackTrace();
423
@NonNull public String getThreadName();
424
}
425
```