CodenameOne - how to catch HTTP 404 error using Terse REST API - codenameone

How can I catch an HTTP 404 error using the Terse REST API in CodenameOne? At the moment the default error handler gets this but I would like to display my own message instead. The code I am using is fine if the accountNo exists and I can deal with the resulting JSON, but if not I get the standard error handler displaying the 404 error:
Response<Map> jsonData = Rest.get( URL + "lookup").
jsonContent().
queryParam("account",accountNo).
getAsJsonMap();

This seems to be a mistake in that version of the method. It should fail silently without a UI Dialog. We'll fix it for the next update.
Notice that jsonData should have the error response code within it as jsonData.getResponseCode().

Related

Subsequent Requests produces SyntaxError: "[object Object]" is not valid JSON React Query

I'm using react query to do a POST request. The request is successful the first time it executes, but keeps producing this error afterwards, even if the page refreshes. It also works if I clear cookies, but only once then the error keeps coming. This is the error message :
SyntaxError: "[object Object]" is not valid JSON
at JSON.parse (<anonymous>)
at AxiosClient.js:22:1
at async loginUser (user.api.js:7:1)
at async Mutation.execute (mutation.ts:200:1)
I have confirmed that in fact my POST body is not empty or undefined.
It sounds like your POST request is returning an object instead of JSON, which is causing the error. Try parsing the response from your POST request before returning it to the caller.

Apache Camel: Unable to get the Exception Body

Whenever there is normal flow in my Camel Routes I am able to get the body in the next component. But whenever there is an exception(Http 401 or 500) I am unable to get the exception body. I just get a java exception in my server logs.
I have also tried onException().. Using that the flow goes into it on error, but still I do not get the error response body that was sent by the web service(which I get when using POSTMAN directly), I only get the request in the body that I had sent to the web service.
Also adding the route:
from("direct:contractUpdateAds")
.to("log:inside_direct:contractUpdateAds_route_CompleteLog?level=INFO&showAll=true&multiline=true")
.streamCaching()
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
.log("before calling ADS for ContractUpdate:\nBody:${body}")
.to("{{AdsContractUpdateEndpoint}}")
.log("after calling ADS for ContractUpdate:\nBody:${body}")
.convertBodyTo(String.class)
.end();
Option 1: handle failure status codes yourself
The throwExceptionOnFailure=false endpoint option (available at least for camel-http and camel-http4 endpoints) is probably what you want. With this option, camel-http will no longer consider an HTTP Status >= 300 as an error, and will let you decide what to do - including processing the response body however you see fit.
Something along those lines should work :
from("...")
.to("http://{{hostName}}?throwExceptionOnFailure=false")
.choice()
.when(header(Exchange.HTTP_RESPONSE_CODE).isLessThan(300))
// HTTP status < 300
.to("...")
.otherwise()
// HTTP status >= 300 : would throw an exception if we had "throwExceptionOnFailure=true"
.log("Error response: ${body}")
.to("...");
This is an interesting approach if you want to have special handling for certains status codes for example. Note that the logic can be reused in several routes by using direct endpoints, just like any other piece of Camel route logic.
Option 2 : Access the HttpOperationFailedException in the onException
If you want to keep the default error handling, but you want to access the response body in the exception handling code for some reason, you just need to access the responseBody property on the HttpOperationFailedException.
Here's an example:
onException(HttpOperationFailedException.class)
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
// e won't be null because we only catch HttpOperationFailedException;
// otherwise, we'd need to check for null.
final HttpOperationFailedException e =
exchange.getProperty(Exchange.EXCEPTION_CAUGHT, HttpOperationFailedException.class);
// Do something with the responseBody
final String responseBody = e.getResponseBody();
}
});

Thunderbird Lightning caldav sync doesn't show any data/events

when i try to synchronize my caldav server implementation with Thunderbird 45.4.0 and Lightning 4.7.4 (one particular calendar collection) it doesnt show any data or events in the calendar though the last call of the sequence provided the data.
In the Thunderbird error log i can see one error:
Zeitstempel: 07.11.16, 14:21:12
Fehler: [calCachedCalendar] replay action failed: null,
uri=http://127.0.0.1:8003/sap/sports/webdav/appsvc/webdav/services/
server.xsjs/cal/_D043133/, result=2147500037, op=[xpconnect wrapped
calIOperation]
Quelldatei:
file:///Users/d043133/Library/Thunderbird/Profiles/hfbvuk9f.default/
extensions/%7Be2fda1a4-762b-4020-b5ad-a41df1933103%7D/calendar-
js/calCachedCalendar.js
Zeile: 327
the call sequence is as follows (detailed content via gist-links):
Propfind Request - Response
Options Request - Response
Propfind Request - Response
Report Request - Response - Response Raw
The synchronization with other clients like macOS-calendar and ios-calendar works in principle and shows the data. Does anyone has a clue what is going wrong here?
Not sure whether that is the cause but I can see two incorrect things:
a) Your <href/> property has trailing spaces:
<d:href>/sap/sports/webdav/appsvc/webdav/services/server.xsjs/cal/_D043133/EVENT%3A070768ba5dd78ff15458f1985cdaabb1.ics
</d:href>
b) your ORGANIZER property is not a valid URI
ORGANIZER:_D043133
i was able to find the cause of the above issue by debugging Thunderbird as propsed by Philipp. The Report Response has http status code 200, but as it is a multistatus response Thunderbird/Lightning expects status code 207 ;-)
Thanks for the hints!

MEAN RESTful application error handling server crashes

I've just followed a tutorial for creating a simple RESTful api using the MEAN stack from the heroku webpage. What I did was just cloning the repo that contains the sample code, added my mongodb_uri from mLab and then run the app locally (npm start).
It works perfectly, but when I try to make an invalid entry (not providing name and last name to a contact) the express server crashes and the entry is made on my database (which is inconsistent).
I've opened an issue on the github repo but I got no answers, I think that there must be something wrong with the error handling but I don't know what it might be.
Here it is what I get when the server crashes:
ERROR: Invalid user input
/Users/nanop/Desktop/mean-contactlist/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (/Users/nanop/Desktop/mean-contactlist/node_modules/express/lib/response.js:719:10)
at ServerResponse.send (/Users/nanop/Desktop/mean-contactlist/node_modules/express/lib/response.js:164:12)
at ServerResponse.json (/Users/nanop/Desktop/mean-contactlist/node_modules/express/lib/response.js:250:15)
at /Users/nanop/Desktop/mean-contactlist/server.js:72:23
at /Users/nanop/Desktop/mean-contactlist/node_modules/mongodb/lib/collection.js:421:18
at handleCallback (/Users/nanop/Desktop/mean-contactlist/node_modules/mongodb/lib/utils.js:96:12)
at /Users/nanop/Desktop/mean-contactlist/node_modules/mongodb/lib/collection.js:726:5
at /Users/nanop/Desktop/mean-contactlist/node_modules/mongodb-core/lib/connection/pool.js:428:18
at nextTickCallbackWith0Args (node.js:433:9)
And finally this is the handleError method defined which I think it's ok:
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}
This is the repo I refer to: https://github.com/chrisckchang/mean-contactlist

Adding 403 Exception view to CakePHP application

I am trying to throw a 403 (Forbidden error) in my controller. When the exception is thrown, I would like to display the associated view. I was under the assumption that if the error is one of the built in exceptions, this would be pretty easy. I throw the exception like this:
throw new ForbiddenException("You do not have permission to view this page.");
I also created a view called "error403.ctp" in the app/view/Errors folder (it already contained 400 and 500). The problem is that when the error is thrown, it displays the error400.ctp view instead. Do I have to create custom exceptions for a built in error? What am I doing wrong.
From http://book.cakephp.org/2.0/en/development/exceptions.html#exception-renderer
"For all 4xx and 5xx errors the view files error400.ctp and error500.ctp are used respectively."
So you aren't doing anything wrong, that's just the default CakePHP behavior. As to how to change it so that you can have a 403 page separate from the other 4XX errors, see CakePHP 2.0 - How to make custom error pages?
I don't have the exact cake version you are using, so I'll use links to docs of version 2.3, but it should apply to any version 2.x.
If you look at the default ExceptionRenderer construct, you get this from the description
Creates the controller to perform rendering on the error response. If the error is a CakeException it will be converted to either a 400 or a 500 code error depending on the code used to construct the error.
And clear enough, from the code of that function, all errors get mapped to that:
$method = 'error500';
if ($code >= 400 && $code < 500) {
$method = 'error400';
}
You'll have to create a custom Exception Renderer if you want to use other views. Also, keep in mind that when using debug < 1, you'll only get 500 error pages
Captures and handles all unhandled exceptions. Displays helpful framework errors when debug > 1. When debug < 1 a CakeException will render 404 or 500 errors. If an uncaught exception is thrown and it is a type that ExceptionHandler does not know about it will be treated as a 500 error.

Resources