json response callback load store extjs - json

I have a JSON store that load data from a PHP script. This script call a Web Service and sometimes it get some errors and I need to capture them and show them in my app.
In my script I print this line when I get an error:
echo '{"success": "false", "error": "'.$res->state->Description.'"}';
In my app I have this code to load the store
targheStore.load({
params: { targa: searchForm.getValues().targa },
callback: function(records, operation, success) {
Ext.getBody().dom.style.cursor = "default";
if(!success){
$("#message2").slideDown('fast');
setTimeout(function() {
$("#message2").slideUp('medium')
}, 2700);
}
}
});
The jQuery code is to show a message "No record found" from the top, but I want to show the error message that I receive from json.

Inside of the operation argument is a request and response object. Use the response object as you would any Ajax response should allow you to handle your messages the way you'd like.
I suggest declaring a globally available handler for processing operation to look for JSON.parse(response.responseText).hasOwnProperty("error") and doing your custom operation in that way.
If you're not using JSONP for communication you can stuff your message in the raw text returned from an HTTP error code (400+) and the {error:} handler in your ajax would be the best way to route errors.

Related

Catch return json from POST with Axios when error 400 (Bad Request) occurs

I am making an http request in an api using React Native with Axios, I can get json and parsear it when the callback is 200, however, for example, when I call a method, for example, to register the user and step an email from a user who is already registered, he returns me an error 400 (Bad Request) but he also brings a json with the error message ("user already registered"). I need to get this error message since it is variable in the API and show to the user, but when I try to give it a console.log I get the following error:
json's return is this:
and my call code looks like this:
How to get this json even with return 400 in catch?
Thank you.
inside of your catch Block, the error object also provides you with a response body
//... your request here
.catch(error => {
console.log('response: ', error.response.data);
});
console.log(error) is calling the toString method of the error object which doesn't show you the response body.
error.response.data should give you the right content. Take a look at this part of the axios docs

VSCode JSON language server unhandled method

I posted this last week and have made progress since, where I've discovered the packages that VSCode's JSON support is delivered via extensions:
https://github.com/vscode-langservers/vscode-json-languageserver
https://github.com/Microsoft/vscode-json-languageservice
and all the rest. I'm trying to reuse this in an Electron (NodeJS) app. I'm able to fork a process starting the language server and initialize it:
lspProcess = child_process.fork("node_modules/vscode-json-languageserver/out/jsonServerMain.js", [ "--node-ipc" ]);
function initialize() {
send("initialize", {
rootPath: process.cwd(),
processId: process.pid,
capabilities: {
textDocument: true
}
});
}
lspProcess.on('message', function (json) {
console.log(json);
});
and I see that console.log firing and showing it seems to be up correctly.
My thoughts are that I just want to send a textDocument/didChange event as per the LSP:
send('textDocument/didChange', {
textDocument: TextDocument.create('foo://bar/file.json', 'json', 0, JSON.stringify(data))
});
where data is a JSON object representing a file.
When I send that message and other attempts at it I get
error: {code: -32601, message: "Unhandled method textDocument/didChange"}
id: 2
jsonrpc: "2.0"
Any idea what I'm doing wrong here? My main goal is to allow edits through my Electron app and then send the updated JSON to the language server to get schema validation done.
EDIT: I'm even seeing unhandled method initialized when I implement connection.onInitialized() in the jsonServerMain.js.
EDIT2: Update, I figured out where I was going wrong with some of this. initialized and textDocument/didChange are notifications, not requests.
EDIT2: Update, I figured out where I was going wrong with some of this. According to the LSP, initialized and textDocument/didChange are notifications, not requests. Requests have an id field that notifications don't, so when sending a notification, remove the ID field.

How to return values in Invoke json response

I am trying to design a hyperledger chaincode, that is accessed through a web API, which passes json objects to the code. However, whenever I do an invoke method, I cannot actually return values to the user in the json response.
For instance, here is some sample code:
func (t *TLCChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
//Do some stuff
return []byte("Some string"), nil
}
And some sample code for returning an error
func (t *TLCChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
//Try to do some stuff
//Get some sort of error
return nil, errors.New("someError")
}
however both of these return a message like this, with the message always being some random character string like below (I suspect a hash of some sort):
{
"jsonrpc": "2.0",
"result": {
"status": "OK",
"message": "1e1123e3-b484-4120-a28e-c3a8db384557"
},
"id": 11
}
As you can see, this response contains neither the response I returned (as in the first case), or the error I returned (in the second case). How would I go about getting the returned bytes, or the returned error into the returned json?
Edit: Please note that if I call an invoke method from another chaincode, it receives the correct return values. It's only when it's returned to the user that it fails to work properly.
“Invoke” is not a synchronous call. Peer generates this OK message immediately when it receives your Web request.
Later, when Validation peers will try to generate new block, this “invoke” method will be executed together with other cached transactions.
In its turn chaincode-to-chaincode calls are synchronous and executed simultaneously.
As a workaround we use another Query request to check the status of this submitted Invoke. It would be great if anybody can propose better solution.
If you need to get a return value as soon as the Invoke is processed (included in a block), your best bet is to use some events (for the moment I guess).
In your chaincode, just setup the event with:
func (stub *ChaincodeStub) SetEvent(name string, payload []byte) error
GoDoc
You may be able to listen for events in your application using the SDK or protobuf messages directly. I'm doing it like this on the developer preview; but it seems that the standard way to retrieve Invoke result is to poll the blockchain via Queries.
There is a related GitHub issue here.

Angular resource 404 Not Found

I've read other posts that have similar 404 errors, my problem is that I can correctly query the JSON data, but can't save without getting this error.
I'm using Angular's $resource to interact with a JSON endpoint. I have the resource object returning from a factory as follows:
app.factory('Product', function($resource) {
return $resource('api/products.json', { id: '#id' });
});
My JSON is valid and I can successfully use resource's query() method to return the objects inside of my directive, like this:
var item = Product.query().$promise.then(function(promise) {
console.log(promise) // successfully returns JSON objects
});
However, when I try to save an item that I've updated, using the save() method, I get a 404 Not Found error.
This is the error that I get:
http://localhost:3000/api/products.json/12-34 404 (Not Found)
I know that my file path is correct, because I can return the items to update the view. Why am I getting this error and how can I save an item?
Here is my data structure:
[
{
"id": "12-34",
"name": "Greece",
"path": "/images/athens.png",
"description": ""
},
...
]
By default the $save method use the POST verb, you will need to figure out which HTTP verbs are accepted by your server en order to make an update, most modern api servers accept PATCH or PUT requests for updating data rather than POST.
Then configure your $resource instance to use the proper verb like this :
app.factory('Product', function($resource) {
return $resource('api/products.json', { id: '#id' }, {'update': { method:'PUT' }});
});
check $resource docs for more info.
NOTE: $resource is meant to connect a frontend with a backend server supporting RESTful protocol, unless you are using one to receive data & save it into a file rather than a db.
Otherwise if you are only working with frontend solution where you need to implement $resource and have no server for the moment, then use a fake one, there is many great solutions out there like deployd.
You probably don't implement POST method for urls like /api/products.json/12-34. POST method is requested from angular for saving a new resource. So you need to update your server side application to support it and do the actual saving.
app.factory('Product', function($resource) {
return $resource('api/products.json/:id', { id: '#id' });
});
Try adding "/:id" at the end of the URL string.

Get real response of ngResource save()

I have the following situation:
I use ngResource to save some data to the mysql database and after the successfull save() I want to log the json response the server sends to me:
Document.save({}, postData, function(response){
console.log(response);
});
This does not result in a simple response, but in something like an object with its own methods. I want some smple output like the response.data after an $http.$get:
{
"docClass":"testets",
"colCount":1,
"columns":null,
"groupid":7,
"id":19,
"lang":"de",
"title":"test",
"version":1409849088,
"workflow":"12234"
}
Greets
Check out this answer
Promise on AngularJS resource save action
So I think in your case you need to do
var document = new Document(postData);
document.$save()
.then(function(res){});
But also from the link I provided
This may very well means that your call to $save would return empty reference. Also then is not available on Resource api before Angular 1.2 as resources are not promise based.