Server side errors handling with angular-formly - angularjs

I'm looking for solution on how I can display errors that the server respond, this is the respond for every invalid submission so I want to make the error handler in the app level and not in a controller.
I want to display the errors both on the FORM level and on the field level.
I have a REST API that in case of error return the following JSON object:
{
"message": "Validation error: Validation notEmpty failed,\nValidation error: Validation isEmail failed",
"errors": [
{
"field": "username",
"message": "Validation notEmpty failed"
},
{
"field": "email",
"message": "Validation isEmail failed"
}
]
}
How can I create a service that display the errors in case there is any?
Thanks

So, i created this for another answer. Let me know if this sort of a setup works for you. Here, the error is intended to be displayed on response from the server after button click. You can modify it accordingly.
I have given the field a custom template as follows:
formlyConfigProvider.setWrapper({
name: 'inputWrapper',
template: '<div ng-class="to.changeColor==\'red\'? \'redBorder\' : \'otherBorder\'"><formly-transclude></formly-transclude>{{to.keyVal}}</div>'
});
The form elements are defined through a schema format to allow each element to be individually accessed.
vm.schema={
"schema": {
"coolValue" : [{
"key": "coolValue",
"type": "input",
"wrapper": ['inputWrapper'],
"templateOptions": {
"type" : "text",
"label": 'Cool Value',
"keyVal":"",
"changeColor":"green"
}
}]
}
};
Finally, the onSubmit function
function onSubmit() {
//Do whatever you want here
//Let's say your server returns an error "iNVALID Credentials"
var response={
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization",
}
],
"code": 401,
"message": "Invalid Credentials"
}
};
vm.schema.schema.coolValue[0].templateOptions.changeColor="red";
vm.schema.schema.coolValue[0].templateOptions.keyVal=response.error.message;
}
});
You can essentially pass any error message or response from the server here.
The CSS contains a class to add a red border to the field.You are free to disable this.Feel free to ping if you need anything in this area as well.
Here is a DEMO

Related

How to I can custom exception message from FileInterceptor?

I want custom exception from FileInterceptor.
Here my lines of code:
#Post('single')
#UseInterceptors(
FileInterceptor('file', { limits: {
files: 1
}}),
)
async uploadFile(#UploadedFile() file, #GetUser('id') userId: number, #Body() dto) {
this.logger.log('Upload file');
file.createdBy = userId;
file.oldFileName = dto.oldFileName;
return this.client.send('upload_file', file);
}
I pass in body with file attribute, it is 1 array files (there are 2 files)
I got message:
{
"response": {
"statusCode": 400,
"message": "Too many files",
"error": "Bad Request"
},
"status": 400,
"message": "Too many files",
"name": "BadRequestException"
}
I want custom that message like to this:
{
"code": 400,
"message": "Too many files"
}
Please help me a solution. Thanks
you can try this to custom your error

change the header Content-Type to application/cloudevents+json when publishing to event grid

I'm using the trigger "When a HTTP request is received" to then publish multiple events to the event grid using the "Publish Event" action. The For loop works fine to split up the JSON that gets in and create the event to publish but still that publish fails with
{
"error": {
"code": "UnsupportedMediaType",
"message": "The Content-Type header is either missing or it doesn't have a valid value. The content type header must either be application/cloudevents+json; charset=utf-8 or application/cloudevents-batch+json; charset=UTF-8. Report 'edf36bbd-9221-4882-8a29-2264ffb16d72:3:3/6/2020 2:18:20 PM (UTC)' to our forums for assistance or raise a support ticket.",
"details": [
{
"code": "InvalidContentType",
"message": "The Content-Type header is either missing or it doesn't have a valid value. The content type header must either be application/cloudevents+json; charset=utf-8 or application/cloudevents-batch+json; charset=UTF-8. Report 'edf36bbd-9221-4882-8a29-2264ffb16d72:3:3/6/2020 2:18:20 PM (UTC)' to our forums for assistance or raise a support ticket."
}
]
}
}
I assume that the header from the input is used when publishing so I tried to change the header when publishing by changing the header in the Publish_Event block as follows (directly in code view as it is not supported in the UI) so I get the following (headers part is added):
"Publish_Event": {
"inputs": {
"body": [
{
"data": "#items('For_each_2')",
"eventType": "company-location",
"id": "ID : #{items('For_each')['businessId']}",
"subject": "Company Location changed"
}
],
"headers": {
"Content-Type": "application/cloudevents+json; charset=utf-8"
},
"host": {
"connection": {
"name": "#parameters('$connections')['azureeventgridpublish']['connectionId']"
}
},
"method": "post",
"path": "/eventGrid/api/events"
},
"runAfter": {},
"type": "ApiConnection"
}
But this is not working neither. Didn't find an action to make the change.
My full flow looks like this :
and as test data I have the following JSON I use to send with postman (a bit simplified):
[
{
"id": 3603,
"businessId": "QQTADOSH",
"locations": [
{
"id": 5316,
"businessId": "A-yelr3g"
},
{
"id": 5127,
"businessId": "A-c7i8gd"
},
{
"id": 5403,
"businessId": "A-fjdd2y"
},
{
"id": 6064,
"businessId": "A-rqvhz8"
}
]
},
{
"id": 3118,
"businessId": "Cr11_Macan_111qa",
"locations": [
{
"id": 4563,
"businessId": "A-3bv860"
}
]
}
]
Looks like the Official Event Grid Publish Connector doesn't support Cloud Events Schema.
You can set the topic to accept Event Grid Schema but I believe this is possible only at the time of creation.
Its best to open a feature request on UserVoice to add support for this and in the meantime, a workaround would be to use an HTTP Action to Post to Custom Topic instead.
But do note that the workaround would involve building the event payload to send (and things like fetching the access key from Key Vault instead of storing it in your workflow directly).

How to troubleshoot ASK ChangeReport failing with INVALID_REQUEST_EXCEPTION

Summary: I am getting an INVALID_REQUEST_EXCEPTION response when attempting to submit a ChangeReport event.
I'm troubleshooting with postman.
POSTing to: https://api.amazonalexa.com/v3/events
One header: Authorization with my token (if this is wrong, I get the correct error)
My body:
{
"event":{
"header":{
"messageId":"06a6278a-0c38-47e5-90e9-12eef0205487",
"namespace":"Alexa",
"name":"ChangeReport",
"payloadVersion":"3"
},
"endpoint":{
"scope":{
"type":"BearerToken",
"token":"XXX My Token XXX"
},
"endpointId":"BedroomLight"
},
"payload":{
"change": {
"cause" : {
"type" : "PHYSICAL_INTERACTION"
},
"properties":[
{
"namespace": "Alexa.PowerController",
"name": "powerState",
"value": "ON",
"timeOfSample": "2019-03-09T15:22:48Z",
"uncertaintyInMilliseconds": 500
}]
}
}
}
}
The response:
{
"header": {
"namespace": "System",
"name": "Exception",
"messageId": "bb7a3bb7-5c2c-4568-8a31-ae24a075f15e"
},
"payload": {
"code": "INVALID_REQUEST_EXCEPTION",
"description": "The request was malformed."
}
}
My input passes the schema validation.
I've tried substituting known invalid values to see if I could shift the error message and narrow down the root cause.
I compared to other code examples in Github and I'm not seeing an obvious error.
I'm not sure how to narrow the problem scope.
Contrary to my understanding above, I was not using the correct BearerToken. I was using the original OAuth code provided in the grant response (I didn't understand the LoginWithAmazon/LWA portion of the security exchange).
The further mistake that made this difficult was the lack of a security error. When I created the Authorization header, I left out the type (Bearer) and just had my value in the value area of the header, which might have been the base reason for the format error.

Gmail API, cannot remove "SENT" label from email

I cannot remove the "SENT" label from any email.
I used PHP classes but it doesn't matter because it occurs even in test page of users_messages.modify.
This is my PHP code:
$mods = new Google_Service_Gmail_ModifyMessageRequest();
$mods->setAddLabelIds(['UNREAD']);
$mods->setRemoveLabelIds('SENT');
$message = $gmailService->users_messages->modify($userId, $messageId, $mods);
I think it could be a general Gmail API error.
I can remove all the others labels but not "SENT". Try it with the follow "Request body":
{
"removeLabelIds": ["SENT"],
"addLabelIds": ["UNREAD"]
}
I got this ERROR 400 reply from the server:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalidArgument",
"message": "Invalid label: SENT"
}
],
"code": 400,
"message": "Invalid label: SENT"
}
}
According to this google forum, there is no way of removing the SENT label in Gmail API.

Gmail api returns 404 error when calling message.get

Gmail API history.list is returning messageId's that return 404 when message.get is called.
I call history.list with "INBOX" label and "history/messagesAdded" fields. I then call message.get with each of the messageId's returned. Some of them return valid messages, others return the following exception:
Google_Service_Exception
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "Not Found"
}
],
"code": 404,
"message": "Not Found"
}
}
What would cause this? It seems like we just retrieved the messageId there isn't enough time for them to now be permanently deleted.
As explained in the comments, this can happen if the message was deleted. This can be checked in the messagesDeleted array return by gmail's history.list, just make sure you send the appropriate historyTypes (or doesn't send any at all).
{
"history": [
{
"id": "69014",
"messagesAdded": [
{
"message": {
"id": "165a2cd1a5b308b9",
"threadId": "1659e85b88e80e7b",
}
}
]
},
{
"id": "69024",
"messagesDeleted": [
{
"message": {
"id": "165a2cd1a5b308b9",
"threadId": "1659e85b88e80e7b",
}
}
]
}
}

Resources