I'm trying to use Retrofit as my remote API client. I implement dependency injection in my project with Injectable, then I register the Dio class like this.
@singleton
class TSApiDio extends DioForNative {
TSApiDio() {
_configureOptions();
_configureInterceptors();
}
void _configureOptions() {
options.baseUrl = TSNetworkConstants.baseNewsAPIUrl;
options.connectTimeout = TSNetworkConstants.connectionTimeout;
options.receiveTimeout = TSNetworkConstants.receiveTimeout;
options.responseType = ResponseType.json;
}
void _configureInterceptors() {
interceptors.add(LogInterceptor());
}
}
Notice that I register my LogInterceptor
in TSApiDio's constructor. Here is the LogInterceptor.
class LogInterceptors extends Interceptor {
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
log('=====================================================');
log("[RESPONSE]: ${jsonEncode(response.data)}", name: "SUCCESS RESPONSE");
log('=====================================================');
return handler.next(response);
}
@override
void onError(DioError err, ErrorInterceptorHandler handler) {
log('=====================================================');
log("[ERROR]: ${err.message}", name: "NETWORK ERROR", error: err.error);
log('=====================================================');
switch (err.type) {
case DioErrorType.connectTimeout:
case DioErrorType.sendTimeout:
case DioErrorType.receiveTimeout:
throw TSException("ERROR FROM INTERCEPTOR");
case DioErrorType.response:
throw TSExceptionWithResponse(1, "TEST ERROR MESSAGE", []);
case DioErrorType.cancel:
break;
case DioErrorType.other:
throw TSException("ERROR FROM INTERCEPTOR");
}
super.onError(err, handler);
}
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
dynamic body;
body = options.queryParameters;
if (options.data != null) {
body = options.data;
}
if (body is Map) {
body = json.encode(body);
}
log('=====================================================');
log("[REQUEST]: ${jsonEncode(body)}", name: "SUCCESS RESPONSE");
log('=====================================================');
return handler.next(options);
}
}
Then I try to hit newsapi.org, but the LogInterceptor was not executed. I also set a breakpoint for the debugger, on each of the overridden functions (onError, onRequest, onResponse) and none of them are executed.
I also try what someone already did in this, but unfortunately nothing different. I wonder what step am I missing in registering the interceptor. Can anyone explain? Or can anyone give another example of registering the interceptors with dependency injection?
There's no warning or error log in this problem.
Thanks in advance.
I've found the answer. This issue may sound silly.
I misregistered the interceptor. The one that I made is called LogInterceptors
and there is actually a built-in class called LogInterceptor
from Dio.
I registered LogInterceptor
class instead of the LogInterceptors
, the one that I made.