how to catch postman assertion error and store in a variable - error-handling

i am using Postman and I have some tests(assertions) in my request. When any test fails, i get an error like the following:-
AssertionError: expected response to have status code 400 but got 200
I want to store this exact error text in a string variable i-e my variable should have the value
MyVariable = AssertionError: expected response to have status code 400 but got 200
I was expecting a postman built-in variable which stores this error but didnt find any.

Using try catch
let error;
pm.test("Status code is 200", function () {
try {
pm.response.to.have.status(200);
}
catch (err) {
error = err
}
});
const {message} = error;
console.log(message)
After that you can set a variable as
pm.environment.set("message",message)

Related

Sending response in async function

I need to return an array of labels, but I can only return 1 of the labels so far. The error which I get is "Cannot set headers after they are sent to the client". So I tried res.write and placed res.end after my for loop then I get the obvious error of doing a res.end before a res.write. How do I solve this?
for(let i=0;i<arr.length;i++){
request.get(arr[i], function (error, response, body) {
if (!error && response.statusCode == 200) {
myfunction();
async function myfunction(){
const Labels = await Somefunctioncallwhoseresponseigetlater(body)
res.send(Labels);
}
}
});}
New code-
async function getDataSendResponse(res) {
let allLabels = [];
for (let url of arr) {
let body = await got(url).buffer();
var imgbuff= Buffer.from(body,'base64')
const imageLabels = await rekognition.detectLabels(imgbuff);
allLabels.push(...imageLabels);
}
res.send(allLabels);
}
The error I have with this code is
"Resolver: AsyncResolver
TypeError: Cannot destructure property Resolver of 'undefined' or 'null'."
You are trying to call res.send() inside a for loop. That means you'll be trying to call it more than once. You can't do that. You get to send one response for any given http request and res.send() sends an entire response. So, when you try to call it again inside the loop, you can the warning you see.
If what you're trying to do is to send an array of labels, then you need to accumulate the array of labels first and then make one call to res.send() to send the final array.
You don't show the whole calling context here, but making the following assumptions:
Somefunctioncallwhoseresponseigetlater() returns a promise that resolves when it is done
You want to accumulate all the labels you collected in your loop
Your Labels variable is an array
Your http request returns a text response. If it returns something else like JSON, then .text() would need to be changed to .json().
then you can do it like this:
const got = require('got');
async function getDataSendResponse(res) {
let allLabels = [];
for (let url of arr) {
let body = await got(url).buffer();
const labels = await Somefunctioncallwhoseresponseigetlater(body);
allLabels.push(...labels);
}
res.send(allLabels);
}
Note, I'm using the got() library instead of the deprecated request() library both because request() is not deprecated and because this type of code is way easier when you have an http library that supports promises (like got() does).

ExpressJS - res.status(500) returning undefined so I can't call send on it

I have some code that usually works, but twice now has produced the following error:
TypeError: Cannot read property 'send' of undefined
The code is:
app.user.get('/status.json', mGatewayTimeout, function (req, res) {
var user = req.user
var qs = cu.querystring.parseUrl(req.url)
if (user.apps && user.apps.beeminder && user.apps.beeminder.access_token) {
if (bsCache[user.username] && !qs.force) {
res.send(bsCache[user.username])
} else {
var bee = new Bee({access_token: req.user.apps.beeminder.access_token})
bee.getUserSkinny(function (err, bm_user) {
if (err) {
bsCache[user.username] = null
return res.status(500).send('error: ' + err.toString())
So that last line produces the TypeError when it tries to call .send on res.status(500).
I've left in a whole bunch of stuff that is certainly irrelevant, because if I tried to take out everything that I thought was irrelevant, we'd be left with nothing.
Bee is an API client, but one that I wrote, so I'm not sure it isn't doing something weird, except that I can't see how it could be affecting the response object.
Try
res.status(500).send(`error ${err.message}`),
new Error's are objects made from a constructor and one of the properties is message.
Oh man, I'm a fool. I made my own problem here. This was on an endpoint that accesses an external API, and since I'm on heroku I need all requests to take under 30s, so I wrote some timeout code that would send an error then turn various functions like res.send into no-op functions. Problem, of course, was that I didn't proceed to return the res object in those no-ops.
🤦‍♀️

How do I get the message from an API using Flurl?

I've created an API in .NET Core 2 using C#. It returns an ActionResult with a status code and string message. In another application, I call the API using Flurl. I can get the status code number, but I can't find a way to get the message. How do I get the message or what do I need to change in the API to put the message someway Flurl can get it?
Here's the code for the API. The "message" in this example is "Sorry!".
[HttpPost("{orderID}/SendEmail")]
[Produces("application/json", Type = typeof(string))]
public ActionResult Post(int orderID)
{
return StatusCode(500, "Sorry!");
}
Here's the code in another app calling the API. I can get the status code number (500) using (int)getRespParams.StatusCode and the status code text (InternalError) using getRespParams.StatusCode, but how do I get the "Sorry!" message?
var getRespParams = await $"http://localhost:1234/api/Orders/{orderID}/SendEmail".PostUrlEncodedAsync();
int statusCodeNumber = (int)getRespParams.StatusCode;
PostUrlEncodedAsync returns an HttpResponseMessage object. To get the body as a string, just do this:
var message = await getRespParams.Content.ReadAsStringAsync();
One thing to note is that Flurl throws an exception on non-2XX responses by default. (This is configurable). Often you only care about the status code if the call is unsuccessful, so a typical pattern is to use a try/catch block:
try {
var obj = await url
.PostAsync(...)
.ReceiveJson<MyResponseType>();
}
catch (FlurlHttpException ex) {
var status = ex.Call.HttpStatus;
var message = await ex.GetResponseStringAsync();
}
One advantage here is you can use Flurl's ReceiveJson to get the response body directly in successful cases, and get the error body (which is a different shape) separately in the catch block. That way you're not dealing with deserializing a "raw" HttpResponseMessage at all.

Angular5 + HttpClient + Observable + HTTP PUT + 204 NO CONTENT

I have a webapi , which has HTTP PUT method with return result "204 No content" (if success). I try to use Angular5 + HttpClient + Observable to update data.
My code is :
updateUser(user): Observable<object> {
var putUrl = this.userURL + "/" + user.id;
var result = this.http.put(putUrl, user).pipe(
catchError(this.handleError)
);
return result;}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return _throw(
'Something bad happened; please try again later.');
};
I clicked update button and there are no request to server in network tab, there are no console error. Where is am I wrong ?
UPDATE I so stupid, I'm sorry. I should subscibe() to the result
Stupid question, I was hurry.
Should : this.userService.updateUser(user).subscribe();
and all will work correctly.

Exception handling ExchangeWebServices php-ews

I use https://github.com/jamesiarmes/php-ews library to access my exchange account.
If I used correct credentials to create a ExchangeWebServices object, I get accurate response.
$ews = new ExchangeWebServices("outlook.office365.com", "tes#abc.com", "test123");
$request = new EWSType_FindItemType();
$response = $ews->FindItem($request);
But If the credentials are wrong it breaks the site by throwing an exception as
EWS_Exception: SOAP client returned status of 401 in ExchangeWebServices->processResponse()
Is there any way to get the response as "failed" or some boolean value instead of the error message?
There's no way to get the response as a boolean, but you can do something like
$ews = new ExchangeWebServices("outlook.office365.com", "tes#abc.com", "test123");
$request = new EWSType_FindItemType();
try {
$response = $ews->FindItem($request);
} catch (\Exception $e) {
//The response failed.
}
Also, that version of php-ews is out of date and unmaintained. Might I suggest you try https://github.com/Garethp/php-ews