I am working on an Angular 9 project with a Flask backend server. In some of my API's there are multiple checks and areas where it can fail and I want to return custom messages to the frontend but I can't seem to access the error message.
As an example, if this was a basic route:
#app.route('/api/test/<int:test_id>/', method=['PUT', 'OPTIONS])
def test_route(test_id):
if test_id < 0:
abort(400, f'Custom Error Message')
else:
#Query data base, update something, return updated entry...
And this was my service function on the frontend (API_URL refers to the root url for the backend):
callTestRoute(id: number): Observable<any> {
const url = `${API_URL}/test/id/`;
return this.http.put(url, httpOptions);
}
And in my component where I call the service function:
updateEntry(id:number) {
this.db_api.callTestRoute(id).subscribe( success => {
console.log(success);
}, (error: HttpErrorResponse) => {
console.log("API ERROR RESP: ", error);
}
}
In the console, my logged message above outputs
"API ERROR RESP: Error Code: 400
Message: Https failure response for http://slate:3660/test/66/: 400 BAD REQUEST"
however, the network request response shows my custom error message. I cannot access this message within my angular component.
I have tried using jsonify() to return the error in my API like:
return jsonify({'errMsg': "Custom error message"}), 400
but I can still not access the error message, when I try to access error.error or any fields, they all show undefined. How do I return a custom message for failed API requests and how do I access those messages on the frontend?
Related
I have a lambda function that puts items in a dynamodb table. It works perfectly fine with test events.
import boto3
class DBupload:
def __init__(self):
client = boto3.resource('dynamodb')
self.table=client.Table('labels')
def Create_data(self,event):
response=self.table.put_item(
Item={
'instanceID' : event['id'],
'imageID' : event['imageid'],
'labels' : event['labels']
}
)
return{
'statusCode' : response['ResponseMetadata']['HTTPStatusCode'],
'body' : 'Record ' + event['id'] + ' added'
}
def lambda_handler(event, context):
if event:
instance = DBupload()
if event['tasktype'] == "create":
create_result = instance.Create_data(event['data'])
return create_result
else :
return {
'statusCode': '404',
'body': 'Not found'
}
I make a REST API gateway, create a resource, and a POST method, with proxy, and I enable IAM and API key, before deploying it. I then go to usage plans, and add the stage to the usage plan, then deploy once more for good measure.
When I send the exact same request now, through Postman, it throws an Internal Server Error. I can send it through the API Gateway testing function which bypasses auth, and it gives me the following error log
Lambda execution failed with status 200 due to customer function error: 'tasktype'.
Method completed with status: 502
So it looks like it is NOT an API error because the error log references the customer function in lambda. But the Lambda function works perfectly fine when I send my item in as a test-event through lambda. What gives?
Here is the test event btw
{
"tasktype":"create",
"data":{
"id":"testinsanceid",
"imageid":"testimageid",
"labels":{
"labeltype1":"labelname1",
"labeltype2":"labelname2"
}
}
}
Try
if 'tasktype' in event and event['tasktype'] == "create":
This will ensure you're not taking a dependency on something that doesn't exist.
Also print(event) will allow you to ensure the event object is what you expect.
I'm trying to fetch the data from DynamoDB using API Gateway + Lambda from flutter APP.
I'm using AWS Amplify plugins for the same
Link to AWS docs: https://docs.amplify.aws/lib/restapi/getting-started/q/platform/flutter#initialize-amplify-api
When authorization is set to None I'm able to fetch the data successfully
But when I set the authorization type to IAM for API gateway I'm facing the below mentioned error.
post call failed: ApiException(message: The HTTP response status code is [403]., recoverySuggestion:
I/flutter ( 6554): The metadata associated with the response is contained in the HTTPURLResponse.
I/flutter ( 6554): For more information on HTTP status codes, take a look at
I/flutter ( 6554): https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
I/flutter ( 6554): , underlyingException: null)
My Code:
Future<List<ChapterData>> getChapters(String subjectID) async {
String postRequest = '{\"subject_id\":\"' + subjectID + '\"}';
print(postRequest);
try {
RestOptions options = RestOptions(
path: "/getChapterList",
body: Uint8List.fromList(postRequest.codeUnits),
apiName: "getChapterList");
RestOperation restOperation = Amplify.API.post(restOptions: options);
RestResponse response = await restOperation.response;
var chapterData = ChapterData.fromJson(
json.decode(new String.fromCharCodes(response.data)));
return chapterData;
} on ApiException catch (e) {
print('post call failed: $e');
}
}
}
Is there anything I missed adding to the post request since it is failing only when I set the authorization type to IAM.
I didn't find any documentation related to this for flutter/dart. Also, I'm new to flutter
Thanks in Advance
I making a request to the back-end server of the port number 8000. I'm making request from the android emulator. so, instead of localhost i'm using ip address. It is throwing the error as
Failed to load resource: the
http://192.168.0.102:8000/api/facebookuser server responded with a
status of 404 (Not Found)
This is my code
postFacebookData(userdata) {
alert(userdata);
let headers = new HttpHeaders();
headers.append('Content-Type','application/json');
return this.http.post('http://192.168.0.102:8000/api/facebookuser',userdata,{headers: headers})
}
This is from routes file
router.post('/facebookuser', function(req,res) {
console.log('facebook request');
It is not subscribing to the method
this.fbPage.postFacebookData(userData)
.subscribe((data: any) => {
if (data.success) {
alert('Data added sucessfully ' && data.msg);
this.authservices.storeUserData(data.token,data.user);
this.navCtrl.push(EditinfoPage);
}
else {
alert('data is not added');
}
},(err) => {
alert('error in subscribing ' + err);
I'm getting an error message in the cosole from the above code as
error in subscribing [object object]
The error is indicating, that the request cannot find the resource you are trying to request.
Make sure that the IP-Adress for your backend is correct (using ipconfig for instance)
Make sure that the endpoint "api/facebookuser" is correct
Make sure that the EMULATOR is in the same network (e.g. WLAN) than your computer (assuming that the backend is running on localhost)
guys im working on django-rest-social-auth that is here in github
https://github.com/st4lk/django-rest-social-auth
and trying to add google login to my django rest framwork app
first i get code from this url
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id={{CLIENT_ID}}&redirect_uri={{REDIRECT_URL}}&scope=email
then
i send needed parameter like clientId,redirect_uri,provider and code to
http://localhost:8000/api/login/social/jwt/google/
with postman and browser form but :
i get HTTP 400 Bad Request error also i see this in my server console :
raise AuthForbidden(args[0])
social_core.exceptions.AuthForbidden: Your credentials aren't allowed
this is the data that i post :
{
"clientId": "61235520-pn78ds5sds5d21d21jmn1e9.apps.googleusercontent.com",
"redirect_uri": "http://localhost:4200/",
"provider": "google-oauth2",
"code": "4%2Fto7CCGznNFgE-rsssPlEQzV3lY9yjUWW_85YmPWF4OU"
}
why ???
I am using a working project of Angular 2 from a Pluralsight course as a reference to make my first app.
This exisiting app fetchs the data from a Json file.
private _productUrl = 'api/products/products.json';
constructor(private _http: Http) { }
getProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
If I modify the url to my own web service that runs locally "http://localhost:53785/api/Session" and run the angular 2 app, It never reaches the breakpoint that I set in my web service and I get "SyntaxError: Unexpected end of JSON input" error.
In the console I get:
"Failed to load resource: the server responded with a status of 500 (Internal Server Error)"
Response
_body
:
""
headers
:
Headers
ok
:
false
status
:
500
statusText
:
"Internal Server Error"
type
:
2
url
:
"http://localhost:53785/api/Session"
proto
:
Body
Does anyone know why cant I reach my web service?
Thanks