I developed a service, using resttemplate and using this service(clientproject) in another project(server), I am trying to throw the exception from resttemplate and handle at server project,but it is not working.
Here is my code:
public class UserService{
public long createUser(Long servcieId){
long userId =0L;
try
{
response = restTemplate.exchange(url,HttpMethod.POST, request, Object.class);
userId = response.getBody().getUser().getId();
}
catch(RestClientException e){
throw e;
}
return userId;
}
}
Here is my service code:
public Long createUserInPortal(Long serviceId){
try
{
Long userId=userService.createUser(serviceId);
}
catch(RestClientException e){
if(e instanceof HttpStatusCodeException){
String errorResponse=((HttpStatusCodeException)e).getResponseBodyAsString();
logger.error("the error in user service is:"+errorResponse);
}
}
I am getting the following error,"resulted in 422 (Unprocessable Entity); invoking error handler".
I am trying to see the response string in the catch block but it is not reaching this catch block.
well may be its getting inside catch block but gets filtered by
if(e instanceof HttpStatusCodeException){ condition
May be e instance is not of type HttpStatusCodeException there are other possibilities like
} catch (HttpClientErrorException e) {
success = false;
Log.e(TAG, command+" was rejected for URL: "+url, e);
resultCode = e.getStatusCode().value();
response = e.getResponseBodyAsString();
} catch (HttpServerErrorException e) {
success = false;
Log.e(TAG, command+" could not be completed for URL: "+url, e);
resultCode = e.getStatusCode().value();
response = e.getResponseBodyAsString();
} catch (ResourceAccessException e) {
if (attemptsLeft > 0) {
Log.w(TAG, command+" failed I/O, retrying.", e);
return simplePut(baseUrl, url, b, command, payload, attemptsLeft);
}
success = false;
Log.e(TAG, command+" failed I/O for URL: "+url, e);
resultCode = 499;
} catch (RestClientException e) {
success = false;
Log.e(TAG, command+" failed for URL: "+url, e);
resultCode = 599;
}
Related
I am using the strava API for an app. I am making synchronous requests as can be seen by the code below.
try {
RequestQueue queue = Volley.newRequestQueue(context);
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = new StringRequest(Request.Method.GET, urlRequest, future, future);
queue.add(request);
dataResponse = dealWithResponse(future.get());
} catch (ExecutionException e) {
System.err.println(e.getLocalizedMessage());
System.err.println(e.getMessage());
System.err.println(e.toString());
} catch (java.lang.Exception e) {
e.printStackTrace();
}
I want to know how can I get the response code in the event of an error? for example some rides I request have been deleted / are private and i receive a 404 error code. Other times I have run out of API requests and get a code of 403. How can i differentiate between the thrown errors.
Thank you very much for your help!
In your catch clause, where you handle the ExecutionException you can add the following:
if (e.getCause() instanceof ClientError) {
ClientError error = (ClientError)e.getCause();
switch (error.networkResponse.statusCode) {
//Handle error code
}
}
Override parseNetworkError on your request:
StringRequest request = new StringRequest(Request.Method.GET, urlRequest, future, future) {
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
if (volleyError != null && volloeyError.networkResponse != null) {
int statusCode = volleyError.networkResponse.statusCode;
switch (statusCode) {
case 403:
// Forbidden
break;
case 404:
// Page not found
break;
}
}
return volleyError;
}
};
I have this class:
public class ConnectionInterceptor implements Interceptor {
#Override
public Response intercept(#NonNull Chain chain) throws IOException {
Request request = chain.request();
Response response;
try {
response = chain.proceed(request);
} catch (ConnectException e) {
throw new IOException("Ошибка соединения с сервером");
} catch (SocketTimeoutException e) {
throw new IOException("Время ожидания соединения истекло");
} catch (Exception e) {
System.out.println("error: " + e.getMessage());
throw new IOException(e.getMessage());
}
if (response.code() == 500) {
throw new ApiNfpException("Ошибка с кодом 500");
}
return response;
}
}
When I get success response (status 200) in debug mode, I see some strange behavior in Android Studio. The debugger stops on the last catch block.
Step 1: I have set many breakpoints. I send a request to server and get response. I stop on this line:
Step 2: I check the error:
Step 3: I press F9 button and move to next line:
If I remove the third catch block, I stop on the second block. Why does the debugger stop on the catch block if there is seemingly no error?
I have a class to show HTTP's error messages.
According to the throwable it shows a message.
But some time I got null pointer exception
public static void showGeneralErrors(Throwable throwable) {
String message = "";
AppInitialization appInitialization = AppInitialization.getInstance();
if (appInitialization == null) {
return;
}
try {
if (throwable instanceof HttpException) {
if (((HttpException) throwable).code() == 500) {
message = appInitialization.getString(R.string.server_error);
} else {
message = appInitialization.getString(R.string.parsing_problem);
}
} else if (throwable instanceof IOException) {
message = appInitialization.getString(R.string.internet_error);
}else if(throwable instanceof SSLHandshakeException){
message = appInitialization.getString(R.string.internet_error);
}
if (!TextUtils.isEmpty(message)) {
Toast.makeText(appInitialization, message, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e(">>>>>", "Exception network error handler " + e.getMessage());
} catch (IllegalStateException e) {
Log.e(">>>>>", "IllegalStateException network error handler " + e.getMessage());
} catch (NullPointerException e) {
Log.e(">>>>>", "NullPointerException network error handler " + e.getMessage());
}
}
And error message is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.makeText(Toast.java:298)
And public AppInitialization is:
public class AppInitialization extends Application {
private static AppInitialization mInstance;
public static synchronized AppInitialization getInstance() {
return mInstance;
}
public void onCreate() {
super.onCreate();
mInstance = this;
}
And it comes from retrofit Onfailure method:
GeneralRepo.getCountryFromIp(getContext())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(countryFromIPResponse -> {
//do something
}, throwable -> {
// Where i got error
NetworkErrorHandler.showGeneralErrors(throwable);
});
why i got this error and why try/catch doesn't work?
Put your try catch block on else portion because NullPointerException occur
appInitialization
is coming null so ..
write :
public static void showGeneralErrors(Throwable throwable) {
String message = "";
AppInitialization appInitialization = AppInitialization.getInstance();
if (appInitialization == null) {
return;
}else{
try { if (throwable instanceof HttpException) {
if (((HttpException) throwable).code() == 500) {
message = appInitialization.getString(R.string.server_error);
} else {
message = appInitialization.getString(R.string.parsing_problem);
} } else if (throwable instanceof IOException) {
message = appInitialization.getString(R.string.internet_error); }else if(throwable instanceof SSLHandshakeException){
message = appInitialization.getString(R.string.internet_error); } if (!TextUtils.isEmpty(message)) {
Toast.makeText(appInitialization, message, Toast.LENGTH_SHORT).show(); } } catch (Exception e) {
Log.e(">>>>>", "Exception network error handler " +
e.getMessage()); } catch (IllegalStateException e) {
Log.e(">>>>>", "IllegalStateException network error handler " + e.getMessage()); } catch (NullPointerException e) {
Log.e(">>>>>", "NullPointerException network error handler " +
e.getMessage()); } } }
I am using the great async http library from loopj, but I have run into a small snag.
If the user has no internet connection or loses their connection, the app just won't return anything. This part is expected, but it also doesn't fire the onFailure method.
Also, the code I have used when there is an internet connection does work so there is no problem on the server end.
Here is some code that is stripped down to the minimum. It also doesn't work (I have tested this too)
String url = getString(R.string.baseurl) + "/appconnect.php";
client.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
client.get(url, null, new JsonHttpResponseHandler()
{
#Override
public void onSuccess(JSONArray response)
{
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Throwable e, JSONArray errorResponse)
{
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
}
});
Thanks,
Ashley
You can try this:
In AsyncHttpRequest->makeRequestWithRetries(), add a catch to SocketException like this:
while (retry) {
try {
makeRequest();
return;
} catch (UnknownHostException e) {
if(responseHandler != null) {
responseHandler.sendFailureMessage(e, "can't resolve host");
}
return;
} catch (SocketException e){
// Added to detect no connection.
if(responseHandler != null) {
responseHandler.sendFailureMessage(e, "can't resolve host");
}
return;
} catch (IOException e) {
cause = e;
retry = retryHandler.retryRequest(cause, ++executionCount, context);
} catch (NullPointerException e) {
// there's a bug in HttpClient 4.0.x that on some occasions causes
// DefaultRequestExecutor to throw an NPE, see
// http://code.google.com/p/android/issues/detail?id=5255
cause = new IOException("NPE in HttpClient" + e.getMessage());
retry = retryHandler.retryRequest(cause, ++executionCount, context);
}
}
Yeah, unfortunately the loopj Android library isn't very well designed. If you implement the other onFailure callbacks one of them should fire:
#Override
public void onFailure(Throwable e) {
Log.e(TAG, "OnFailure!", e);
}
#Override
public void onFailure(Throwable e, String response) {
Log.e(TAG, "OnFailure!", e);
}
#Override
public void onFailure(Throwable e, JSONArray errorResponse) {
Log.e(TAG, "OnFailure!", e);
}
Try this:
#Override
protected Object parseResponse(byte[] responseBody) throws JSONException {
return super.parseResponse(responseBody);
}
I have the following on a web servlet:
EDITED:
public String tryGoogleAuthentication(String auth_token){
HttpURLConnection connection = null;
try {
//connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2v1/tokeninfo?access_token={"+auth_token+"}")).openConnection();
connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2/v1/user info")).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer {"+auth_token+"}");
connection.setRequestProperty("Host", "googleapis.com");
//read response
String response = fromInputStreamToString(connection.getInputStream());
System.out.println(response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return CONST.STATUS_OK;
}
In android:
private void googleAuthenticate(){
try {
mOAauthHelper = new OAuthHelper("something.net", "xxxxxxxxxx",
"https://www.googleapis.com/auth/userinfo.profile", "alex://myScheme");
String uri = mOAauthHelper.getRequestToken();
startActivity(new Intent("android.intent.action.VIEW", Uri.parse(uri)));
//Intent i = new Intent(this, GoogleOAUTHActivity.class);
//i.putExtra(GoogleOAUTHActivity.GOOGLE_OAUTH_ENDPOINT_KEY, uri);
//startActivity(i);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
}
}
and
#Override
protected void onNewIntent(Intent intent) {
//super.onNewIntent(intent);
Uri uri = intent.getData();
String oauthToken = uri.getQueryParameter("oauth_token");
String oauthVerifier = uri.getQueryParameter("oauth_verifier");
if(oauthToken != null){
authorizeGoogleSessionToServer(oauthToken);
}
}
After this, I send the request token to my servlet where I tried to get user profile, but with no success.
Could you please tell me what's wrong and why I'm getting error 400 from google?
Thanks.
Unfortunately, I can see a few issues with this already
you should never have curly braces in your URL or even in the Bearer header as stated in the draft.
connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2/v1/userinfo?access_token={"+auth_token+"}")).openConnection()
400 means that you're missing something in your request, there is probably more information about it in the same response as specific error node.
Finally, take care, oauth_verifier param is from OAuth 1.
I suggest you test your request URL's, using the Google OAuth2 playground
Good luck!