I would like to parse the response that my NestJs backend is sending to my Dart front end.
If from NestJs controller I reply with
return new HttpException('Already running..', HttpStatus.PROCESSING);
I receive on Dart's Response object:
Response: {
...
statusCode: 201
body {
"response": "Already running..",
"status":102,
"message": "Already running..",
"name": "HttpException"
}
}
Whereas if I return
throw new HttpExcpetion('Already running..', HttpStatus.PROCESSING)
I receive:
Response: {
...
statusCode: 102
body: ""
}
I would have expected to receive something like the below:
Response: {
...
statusCode: 102
message: "Already running..",
}
Any ideas how the two approaches are different and what should be the proper, consistent way so I know how to parse responses from backend?
Related
What is the right format of the Response for Kinesis Firehose with http_endpoint as destination. Have already gone through the aws link:
https://docs.aws.amazon.com/firehose/latest/dev/httpdeliveryrequestresponse.html#responseformat
I have used the below lambda code in python(integrated in api) as well as with many other options, but keep getting the below error message. The test is performed using the "Test with Demo Data" option
sample code:
def lambda_handler(event, context):
data ={}
headersD = {}
headersD['content-length'] = 0
headersD['content-type'] = 'application/json'
data['requestId'] = 'ed4acda5-034f-9f42-bba1-f29aea6d7d8f'
data['timestamp'] = '1578090903599'
bodyDetail= {}
data['body'] = ''
data['headers'] =headersD
data['statusCode']=200
resp = json.dumps(data)
return resp
error response as seen in the logs:
The response received from the endpoint is invalid. See Troubleshooting HTTP Endpoints in the Firehose documentation for more information. Reason:. Response for request 'request-Id' is not recognized as valid JSON or has unexpected fields. Raw response received: 200 "HttpEndpoint.InvalidResponseFromDestination"
Here is the sample output that worked(in python):
responseBody = {
"requestId": "requestId",
"timestamp": 123456
}
resp = {
"headers": {"Content-Type": "application/json", "Content-Length": 100},
"body": json.dumps(responseBody),
"statusCode": 200
}
return resp
I'm developing a client-server application in Dart and have been following the tutorial. My server code is roughly based on it.
In my server API code, when something goes wrong, I want to throw an exception, for example:
void checkEverything() {
if(somethingWrong)
throw new RpcError(400, "Something Wrong", "Something went wrong!");
}
#ApiMethod(path: 'myservice/{arg}')
Future<String> myservice(String arg) async {
checkEverything();
// ...
return myServiceResponse;
}
and that exception should be processed in the main server, e.g.
// ...
var apiResponse;
try {
var apiRequest = new HttpApiRequest.fromHttpRequest(request);
apiResponse = await _apiServer.handleHttpApiRequest(apiRequest);
} catch (error, stack) {
var exception = error is Error ? new Exception(error.toString()) : error;
if((error is RpcError && error.statusCode==400) {
// My code for creating the HTTP response
apiResponse = new HttpApiResponse.error(
HttpStatus.BAD_REQUEST, "Something went wrong", exception, stack);
}
else {
// standard error processing from the Dart tutorial
apiResponse = new HttpApiResponse.error(
HttpStatus.INTERNAL_SERVER_ERROR, exception.toString(),
exception, stack);
}
}
(snippet, see the tutorial for the complete code sans my error handling).
However, my exception never reaches the above catch clause. Instead, it seems to get caught in _apiServer.handleHttpApiRequest(apiRequest);, which, in turns, throws INTERNAL_SERVER_ERROR (500):
[WARNING] rpc: Method myservice returned null instead of valid return value
[WARNING] rpc:
Response
Status Code: 500
Headers:
access-control-allow-credentials: true
access-control-allow-origin: *
cache-control: no-cache, no-store, must-revalidate
content-type: application/json; charset=utf-8
expires: 0
pragma: no-cache
Exception:
RPC Error with status: 500 and message: Method with non-void return type returned 'null'
Unhandled exception:
RPC Error with status: 400 and message: Something went wrong!
#0 MyApi.myservice (package:mypackage/server/myapi.dart:204:24)
[...]
This is not very specific for the client. I'd like to communicate that an error has happened, not to return a good-looking response. So what is the proper way of handling server-side exceptions in Dart and passing that information to the client?
OK, I think I solved the problem. The throw clause apparently has to be in the API method itself, and not in a subordinate method. I.e.:
#ApiMethod(path: 'myservice/{arg}')
Future<String> myservice(String arg) async {
if(somethingWrong)
throw new RpcError(400, "Something Wrong", "Something went wrong!");
// ...
return myServiceResponse;
}
and not:
void checkEverything() {
if(somethingWrong)
throw new RpcError(400, "Something Wrong", "Something went wrong!");
}
#ApiMethod(path: 'myservice/{arg}')
Future<String> myservice(String arg) async {
checkEverything();
// ...
return myServiceResponse;
}
Whenever I attempt to make a PUT Request to Reddit API in order to add a friend, it fails and claims a JSON Parse Error 'JSON_PARSE_ERROR'. Nothing I do is working. Here is how I form the request.
Endpoint: /api/v1/me/friends/username
>>> Endpoint URL: PUT https://oauth.reddit.com/api/v1/me/friends/micheal
Authorization: Bearer <Access_Token>
// The response given:
{"fields": ["json"], "explanation": "unable to parse JSON data", "reason": "JSON_PARSE_ERROR"}
I have also tried the /api/friend/username endpoint and nothing works.
I had exactly the same problem, and your question led me to the solution.
The endpoint is expecting a json payload ACTUALLY NAMED "json." I'm not sure what language you're using, this is what it looks like in Node:
var options = {
url: 'https://oauth.reddit.com/api/v1/me/friends/mynewfriend',
headers: {
'User-Agent': 'Appname/1.0 by username',
'Authorization': "bearer " + <Access_Token>
},
json: {
'name': 'mynewfriend',
'notes': 'whatever notes you want to put',
}
};
request.put(options, function(error, response, body) {
blah blah blah
}
the json itself is described in https://www.reddit.com/dev/api/#PUT_api_v1_me_friends_{username}
With ActionCable, how can I respond with an error after receiving data from a client?
For example, when the client fails to authenticate, ActionCable throws UnauthorizedError which responds with a 404. I want to respond with a 422, for example, when the data that the client sent is invalid.
ActionCable.server.broadcast "your_channel", message: {data: data, code: 422}
Then in your.coffee file:
received: (res) ->
switch res.code
when 200
# your success code
# use res.data to access your data message
when 422
# your error handler
From what I could gather there's no "Rails way" to do this, the answer given by #Viktor seems correct. In summary: ensure all messages are broadcasted with both data and code, then switch by code in the client.
For a more modern and ES6 example see below:
In rails:
require 'json/add/exception'
def do_work
// Do work or raise
CampaignChannel.broadcast_to(#campaign, data: #campaign.as_json, code: 200)
rescue StandardError => e
CampaignChannel.broadcast_to(#campaign, data: e.to_json, code: 422) # Actually transmitting the entire stacktrace is a bad idea!
end
In ES6:
campaignChannel = this.cable.subscriptions.create({ channel: "CampaignChannel", id: campaignId }, {
received: (response) => {
const { code, data } = response
switch (code) {
case 200:
console.log(data)
break
default:
console.error(data)
}
}
})
I am using trigger URL to run a test case created on Runscope. In response I am getting only details as shown in Runscope documentation. For eg.
Response Sample data:
{
"data": [],
"error": null,
"meta": {"status": "success"}
}
But I need the data in response body retrieved from server for request made.For eg.
{
"Status": "OK",
"Body": [{"userId": 12345,"sessionId": "abcd:1234"}]
}
I am using HttpRequest and HttpResponse for the same.
Why don't you use something like this :
https://www.npmjs.com/package/dyson#installation
It is used to mock results via api .