Catching an error message with retrofit HttpException - android

I'm using Retrofit to make some requests to the API, and when I receive back the response it's usually received from the API in this format if the request is successful
Successful Response
{
"success": 1,
"error": [],
"data": [
// Some data..
]
}
And if there is an error, the response will go like this
Unsuccessful Response
{
"success": 0,
"error": [
"Password is incorrect"
],
"data": []
}
The problem now in case there is an unsuccessful request, it comes with error code 403, so Retrofit classifies it as an Exception and throws an HttpException, then i have no way to catch the password is incorrect message attached in the json response.
Is there any way I still can get the body response even if there is an HttpException?
Update
This is the sample code I'm using
ViewModel
viewModelScope.launch {
try {
val result = myApi.request(requestParam)
}catch (e: HttpException){
// Log the error
}
}

Well, I figured out a way to get back the response from the passed exception.
As I said in the question, this is the code I'm using
Old code sample
viewModelScope.launch {
try {
val result = myApi.request(requestParam)
}catch (e: HttpException){
// Log the error
}
}
However, I didn't know that the response body is passed with the exception, and you can receive it as a string using the errorBody() method as follows.
New code sample
viewModelScope.launch {
try {
val result = myApi.request(requestParam)
}catch (e: HttpException){
val response = e.response()?.errorBody()?.string()
}
}
And from there you can manipulate this string to extract the error message.

Related

Authentication Error while sending POST request through FCM REST API with volley

I am sending a POST request to Firebase Cloud Messaging servers using the endpoint https://fcm.googleapis.com/v1/projects/{PROJECT_NAME}/messages:send so as to send notifications to my app. The problem is i am getting an error 401, AUTHENTICATION ERROR. I have gone through their doc https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages/send?apix=true many times and i can't seem to understand why i am getting this error. I tried testing the endpoint with the Google API explorer on the page and it works fine. Notification is sent to my app. However, sending this same POST request in my code with volley fails with the follow error, in JSON:
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
Here's what i did:
val FCM_POST = "https://fcm.googleapis.com/v1/projects/${Constants.PROJECT_NAME}/messages:send"
val map = mapOf("message" to
mapOf("notification" to
mapOf("title" to "test title",
"body" to "test body")),
"topic" to "testTopic")
val request = object : JsonObjectRequest(
Method.POST,
FCM_POST,
JSONObject(map), {
showDialog.log(TAG, "sendMedicalTipsNotification response: $it")
}, {
val networkResponse = it.networkResponse
if (networkResponse?.data != null) {
val jsonError = String(networkResponse.data)
try {
val jsonObject = JSONObject(jsonError)
showDialog.log(TAG, "sendMedicalTipsNotification error: $jsonObject")
} catch (e: JSONException) {
showDialog.log(TAG, "sendMedicalTipsNotification error: $e")
}
}
}) {
override fun getHeaders(): MutableMap<String, String> {
return mutableMapOf("Authorization" to "Bearer ${Constants.MY_PROJECT_CLOUD_CONSOLE_CLIENT_ID}",
"Content-Type" to "application/json")
}
}
Volley.newRequestQueue(ctx).add(request)
}
As you can see i'm sending my CLIENT_ID and Content Type in request header. I really don't know why i am getting this error

Get multiple response from API in flutter

I have a user registration API written in node but the API gives me three types of responses
If the registration is successful then the below JSON is the response
{
"message": "success",
"ccontent": {
"_id": "5ef7c4c414529241205fb590",
"email": "sam#gmail.com",
"password": "$2b$05$4TFPKJ83O7jSPhjtIIDj1ud5pjhS9GY.I0C.IFlBDyUFsd6i4E3Ci",
"__v": 0
}
}
If the user already exists it just gives me a string response
already-exists
If error occurred
error-occurred
I have a future function to get the response from the API
class RegistrationService {
String registrationUrl = 'http://192.168.1.6:8080/api/user/create';
Future userRegistration(email, password) async {
Response response = await post(registrationUrl,
body: {"email": email, "password": password});
var result = jsonDecode(response.body);
return RegistrationResponse.fromJson(result);
}
}
This works only when the user registration is a success but when it fails error occurs telling unhandled exception 'already-exists' or 'error-occurred'
How can I get all types of responses from the API in this future function?
Thanks in advance.
You could throw an exception in case response is already-exists or error-occurred
class RegistrationService {
String registrationUrl = 'http://192.168.1.6:8080/api/user/create';
Future<Map<String, dynamic> userRegistration(email, password) async {
Response response = await post(registrationUrl,
body: {"email": email, "password": password});
if (userAlreadyExist(response.body)) {
// already-exists response
throws UserAlreadyExistException();
}
else if (errorOccurred(response.body)) {
// error occurred response
throws SomeOtherException();
}
var result = jsonDecode(response.body);
return RegistrationResponse.fromJson(result);
}
}
You would need to implement methods userAlreadyExist and errorOccurred to detect this situation and decide what's the best exception type for every case. You would also need to cath the exception when you call userRegistration so you can react properly.

How to translate my Android code to Swift code for my Firebase function?

From my research, there isn't much help translating Android code to Swift code. With some help, we were able to translate or convert some of the code but it's not quite finished. When I run the code, I get an error:
Response could not be serialized, input data was nil or zero length.
responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
Android code needing converting to Swift code:
public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
ProgressDialog progress;
private void payoutRequest() {
progress = new ProgressDialog(this);
progress.setTitle("Processing your payout ...");
progress.setMessage("Please Wait .....");
progress.setCancelable(false);
progress.show();
// HTTP Request ....
final OkHttpClient client = new OkHttpClient();
// in json - we need variables for the hardcoded uid and Email
JSONObject postData = new JSONObject();
try {
postData.put("uid", FirebaseAuth.getInstance().getCurrentUser().getUid());
postData.put("email", mPayoutEmail.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
// Request body ...
RequestBody body = RequestBody.create(MEDIA_TYPE, postData.toString());
// Build Request ...
final Request request = new Request.Builder()
.url("https://us-central1-myapp.cloudfunctions.net/payout")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("cache-control", "no-cache")
.addHeader("Authorization", "Your Token")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// something went wrong right off the bat
progress.dismiss();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// response successful ....
// refers to response.status('200') or ('500')
int responseCode = response.code();
if (response.isSuccessful()) {
switch(responseCode) {
case 200:
Snackbar.make(findViewById(R.id.layout),
"Payout Successful!", Snackbar.LENGTH_LONG)
.show();
break;
case 500:
Snackbar.make(findViewById(R.id.layout),
"Error: no payout available", Snackbar
.LENGTH_LONG).show();
break;
default:
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
break;
}
} else {
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
}
progress.dismiss();
}
});
}
Swift code used from the above Android code:
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"cache-control": "Your Token"]
Alamofire.request(url, method: .get, headers: headers).validate().responseJSON { (response) in
switch response.result {
case .success(let value):
// you fall here once you get 200 success code, because you use .validate() when you make call.
print(value)
// parse your JSON here.
let parameters : [String: Any] =
["uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]
let postData = try! JSONSerialization.data(withJSONObject: parameters, options: [])
case .failure(let error):
if response.response?.statusCode == 500 {
print("Error no payout available")
print(error.localizedDescription)
} else {
print("Error: couldn't complete the transaction")
print(error.localizedDescription)
}
}
}
How can I convert the Android code into the Swift code or discover what it is I am doing wrong? This code is used to post to the function I have created for Firebase.
Edit
With the help of supplied code in this post, I was able to come up with this code but it is still coming up with the same error:
===========Error===========
Error Code: 4
Error Messsage: Response could not be serialized, input data was nil or zero length.
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
updated swift code
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"cache-control": "Your Token"]
let params : [String: Any] = [
"uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in
switch response.result {
case .success(let JSON):
print("Success with JSON: \(JSON)")
if (response.result.value as? [String:AnyObject]) != nil {
// Access your response here
print(response.result.value!)
}
break
case .failure(let error):
if response.response?.statusCode == 500 {
print("Error no payout available")
print(print("Request failed with error: \(error.localizedDescription)"))
} else {
print("Error: couldn't complete the transaction")
print("\n\n===========Error===========")
print("Error Code: \(error._code)")
print("Error Messsage: \(error.localizedDescription)")
}
}
print("response \(response)")
}
EDIT #2
I edited my method:
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"cache-control": "no-cache",
"Authorization": "Your Token",
"Content-Type": "application/json"]
let parameters : [String: Any] = [
"uid": uid,
"email": self.paypalEmailText.text!
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate(statusCode: 200..<600).responseJSON { (response) in
print("Request: \(String(describing: response.request))") // original url request
print("Result: \(response.result)") // response serialization result
if response.response?.statusCode == 200 {
print("Success with JSON: \(String(describing: response.result.value))")
} else {
let error = (response.result.value as? [[String : AnyObject]])
print(error as Any)
}
print("response \(response)")
}
The response and print outs are:
Request: Optional(https://us-central1-myapp.cloudfunctions.net/payout)
Result: FAILURE
Success with JSON: nil
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
Keep in mind, in my url, my app is not called "myapp" it is just there for protection.
I think there are two issues in the code:
In the Android code, you are setting the parameters uid and email in the request body, whereas in the Swift code, you are setting these parameters in the response body, which is wrong (because by the time you got the response, the request is already completed without the params).
If you want to set a body for the request, the HTTP method (the second parameter to Alamofire.request should be post instead of get.
What you need to do is set the parameters in the request body and set the HTTP method as post, as follows:
let parameters: [String: Any] =
["uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]
Alamofire.request(url, method:.post, parameters:parameters,
encoding: JSONEncoding.default, headers:headers)
Try it out and see if it works.
So I'd do it like this here:
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"cache-control": "Your Token"
]
Alamofire.request(url,
method: .get,
encoding: JSONEncoding.default,
headers: headers).responseJSON
{ response in
switch response.result {
case .success(let JSON):
print("Success with JSON: \(JSON)")
// parse your JSON here something like
if let json = response.result.value as? [String:AnyObject] {
// Access your response here
}
break
case .failure(let error):
print("Request failed with error: \(error)")
}
}
In the success part you should be able to access the JSON and are able to parse it. Can you comment how your reponse object looks like, then I'll comment how you parse it and access the correct elements. I can otherwise only guess.

Gson toJson and ArrayList in Kotlin

Similarly to this question, I would like to convert an object (actually, it is a API response from retrofit) to a json string, so it would be simpler to store it somewhere.
The response structure is something like these:
{
"metadata": {
"count": 0,
"type": "string"
},
"results": [
{
"obj1": {
"param1": "s1",
"param2": "s2"
},
"obj2": {
"param3": 0,
"param4": 0,
"param5": 0
},
"obj3": 0,
"obj4": "27/12/2017"
}
]
}
Using retrofit2, I have the results array stored in a List<MyResponse.Result> and that's the parameter I'm passing to Gson().toJson, like so:
var contentResponse: String = ""
try{
this.contentResponse.plus(Gson().toJson(response))
} catch (e: Exception){
Log.e("Gson error", e.toString())
}
Unfortunately, I'm getting no exception but my contentResponse keeps empty. I`ve tried to use the method in the question mentioned above, but got the same outcome. Any advises?
PS: If there is an easier way to get the retrofit response in a String, it could help as well.
Strings are immutable in JVM. Calling
this.contentResponse.plus(Gson().toJson(response))
is equivalent to
this.contentResponse + (Gson().toJson(response))
This way you can see better that you are not assiging the result to anything. Change it to
this.contentResponse = this.contentResponse.plus(Gson().toJson(response))

Broken server response handling with Moshi

The expected json response from server should be :
{
"teacher": {
"123": {
"_id": "389",
"name": "test_fast_teacher1"
}
}
}
Server returned json with this :
{
"teacher": [
]
}
Anyway to handle this broken json response?
Before I switching from Gson, the teacher object will still be deserialised, just that it will be null. By using Moshi, the error would be threw and I can't proceed with the other json which is serialised correctly.
Please refer to the link for the reply from author.
How about something like this?
Moshi moshi = new Moshi.Builder()
.add(DefaultOnDataMismatchAdapter.newFactory(Teacher.class, null))
.build();
JsonAdapter<Teacher> adapter = moshi.adapter(Teacher.class);
Teacher teacher = adapter.fromJson(json);
// teacher == null
where DefaultOnDataMismatchAdapter is Jesse's code you can copy into your code base.
When the Teacher type comes back in an unexpected format that would produce a JsonDataException, it will default back to your set value (in this case, null).

Categories

Resources