Junior — Middle
Explain the concept of interceptor and its role in software architectures.
sobes.tech AI
Answer from AI
Interceptor is a design pattern that allows intercepting and processing requests or calls before they reach the main logic, as well as after its execution. In software architectures, interceptors are often used to introduce additional behavior, such as logging, authentication, caching, or error handling, without modifying the core code.
In the context of Flutter and working with HTTP requests (for example, with the Dio package), an interceptor allows intercepting requests and responses, modifying them, adding headers, or handling errors centrally.
Example of using an interceptor in Dio:
final dio = Dio();
dio.interceptors.add(InterceptorsWrapper(
onRequest: (options, handler) {
// Add an authorization token to each request
options.headers['Authorization'] = 'Bearer your_token';
return handler.next(options);
},
onResponse: (response, handler) {
// Log successful response
print('Response: \\${response.statusCode}');
return handler.next(response);
},
onError: (DioError e, handler) {
// Handle errors centrally
print('Error: \\${e.message}');
return handler.next(e);
},
));